假设我有一个函数,它在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