简体   繁体   English

循环以从统一数据帧创建新变量

[英]Loop over to create new variables from uniform dataframe

My problem is the following我的问题如下

I want to create variables e_1, e_2, e_3, ... , e_50 which are all composed of 100 draws from the uniform[-1,1]我想创建变量 e_1, e_2, e_3, ... , e_50 它们都由 100 个制服组成 [-1,1]

This means e_1 is a vector of 100 draws from U[-1.1], e_2, .., e_50 as well.这意味着 e_1 是从 U[-1.1]、e_2、..、e_50 中抽取 100 次的向量。

Here is what I thought I could do :这是我认为我可以做的:

periods <- c(1:50)
people <- c(1:100)
for (t in periods){
sprint('e_', t) <- runif(100, -1,1)
}

This did not work, and i am really not sure how to change it to obtain what I want.这不起作用,我真的不知道如何改变它以获得我想要的。

Thank you so much for your help!!非常感谢你的帮助!!

It is better not to create objects in the global environment.最好不要在全局环境中创建对象。 Regarding the issue in the code, the assignment should be based on assign关于代码中的问题,分配应该基于assign

for(t in periods) {
    assign(sprintf('e_%d', t), runif(100, -1, 1))
}

An approach that wouldn't create multiple objects in the global env, would be to create a list with replicate一种不会在全局环境中创建多个对象的方法是创建一个带有replicatelist

lst1 <- replicate(length(periods), runif(100, -1, 1), simplify = FALSE)
names(lst1) <- sprintf('e_%d', periods)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM