假设我有一个函数在 Julia 中进行一些计算并返回一个数据框
using DataFrames, Random
function dummy_df(;theta)
A = randn(100); B = randn(100);
A = A .* theta; B = B .* theta
df_ = DataFrame(A = A, B = B)
return(df_)
end
a = dummy_df(theta = 1)
现在假设我有 theta
的这个值。
tau = range(0.85, 1, length = 10)
所以我想创建一些对象,其中包含为 tau 向量中的每个元素生成的数据帧。 (在 R 中它将是一个列表)
我认为这像来自 R 的列表
a = []
所以我想用所有数据框填充该列表。
所以我正在尝试做一个 for 循环来运行 dummy_df
并像这样存储该数据帧:
for (i,t) in pairs(tau)
a[i] = dummy_df(theta = t)
end
但是我有这个错误:
ERROR: BoundsError: attempt to access 0-element Vector{Any} at index [1]
最佳答案
将项目添加到空列表的语法是 push!,使用 a[i]
只会尝试访问没有任何项目的空列表。
我还用 t
替换了你的 tau
因为我猜你想让 theta 改变每个循环而不是将 tau
送入 dummy_df
.
我设法创建了一个没有错误的数据框列表。
using DataFrames, Random
function dummy_df(;theta)
A = randn(100); B = randn(100);
A = A .* theta; B = B .* theta
df_ = DataFrame(A = A, B = B)
return(df_)
end
tau = range(0.85, 1, length = 10)
a = []
for (i,t) in pairs(tau)
push!(a, dummy_df(theta = t)) #guessing you made a mistake here and meant to put t instead of tau
end
a
的打印输出如下所示,
10-element Vector{Any}:
100×2 DataFrame
Row │ A B
│ Float64 Float64
─────┼──────────────────────────
1 │ 0.958768 -0.302111
2 │ 0.370959 1.12717
3 │ 1.69035 1.45085
4 │ -0.586892 0.258312
5 │ -1.43566 1.01867
6 │ 0.0389977 0.471484
7 │ -0.314276 -0.347831
8 │ -0.00176065 0.494805
⋮ │ ⋮ ⋮
94 │ 0.700048 -1.50753
95 │ -0.154113 1.04487
96 │ -0.716135 -0.883592
97 │ 0.487718 -0.0188041
98 │ 1.01621 0.863817
99 │ -0.578018 0.270933
100 │ 1.89336 -0.837134
85 rows omitted
100×2 DataFrame
Row │ A B
│ Float64 Float64
─────┼─────────────────────────
1 │ 0.388522 -1.18676
关于list - 如何在 Julia 中存储循环结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74061448/