简体   繁体   English

连续向 R 中的数据框添加列

[英]Successively add columns to dataframe in R

I am looking to go through 20 iterations where I add 1 new column to an existing dataframe in each iteration.我希望通过 20 次迭代,在每次迭代中向现有数据帧添加 1 个新列。 The column will be a value from the random uniform distribution between 1 and 100. My actual dataframes are 10000 rows, but the format of the dataframes is as follows:该列将是 1 到 100 之间随机均匀分布的值。我的实际数据帧是 10000 行,但数据帧的格式如下:

df <- data.frame(var1 = c(319, 77, 222, 107, 167),
                  var2 = c(137, 290, 237, 52, 192),
                  class = c(1,1,0,1,0))

Ideally, the columns added will be named var3, var4,...., var21 with each iteration.理想情况下,添加的列将在每次迭代中命名为 var3、var4、....、var21。 I need to fit some models after each iteration as each individual column is added to the dataframe, in order to show how their accuracy declines as more columns are added of information that is not helpful.我需要在每次迭代后拟合一些模型,因为每个单独的列都被添加到数据框中,以显示它们的准确性如何随着添加更多列的无用信息而下降。

df <- data.frame(var1 = c(319, 77, 222, 107, 167),
                  var2 = c(137, 290, 237, 52, 192),
                  class = c(1,1,0,1,0))
for(i in 1:20){
col = paste('var_new_',i)
df[col] = runif(5)
# Add model code here
}
df

Since you already have var1 and var2, you could iterate through 3 to 20 with a for loop:由于您已经有了 var1 和 var2,您可以使用 for 循环遍历 3 到 20:

for (i in 3:20) {
  col_name <- paste0("var", i)
  df[[col_name]] <- runif(5, 0, 100) #5 because df has 5 rows
}

This will create vars3, var4, ...var 20.这将创建 vars3、var4、...var 20。

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

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