简体   繁体   English

如何在循环内在R中的数据框中创建新列并向其中添加新列?

[英]How to create and add new columns to a dataframe in R within a loop?

I want to create a new dataframe and keep adding variables in R with in a for loop. 我想创建一个新的数据框,并在for循环中继续在R中添加变量。 Here is a pseudo code on what I want: 这是我想要的伪代码:

X <- 100  
For(i in 1:X)  
{  
  #do some processing and store it a variable named "temp_var"

  temp_var[,i] <- z 
  #make it as a dataframe and keep adding the new variables until the loop completes  
}

After completion of the above loop the vector "temp_var" by itself should be a dataframe containing 100 variables. 完成上述循环后,向量“ temp_var”本身应为包含100个变量的数据帧。

I would avoid using for loops as much as possible in R . 我会尽量避免在R使用for循环。 If you know your columns before hand, lapply is something you want to use. 如果您事先知道您的专栏,那么请使用lapply

However, if this is constraint by your program, you can do something like this: 但是,如果这是程序的约束,则可以执行以下操作:

X <- 100
tmp_list <- list()
for (i in 1:X) {
    tmp_list[[i]] <- your_input_column
}
data <- data.frame(tmp_list)
names(data) <- paste0("col", 1:X)

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

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