在for循环中的R中创建列 [英] Create columns in R within a for loop
问题描述
我在R中有一个数据框,我想在for循环中创建新的列.最近2天,我尝试了很多事情,但没有成功.最后,我确实找到了一个似乎可行的解决方案,但它似乎不是很简单.我想知道是否有人有更优雅的方法来做到这一点.
抱歉,如果这个问题已经解决,但是我在SO
上找不到类似的问题
这是我的例子.
I have a data frame in R and I would like to create new columns within a for loop. I have tried many things for the last 2 days but without success. At the end, I did find a solution that seems to work, but it doesn't seem very straight forward. I was wondering if anybody has a more elegant way to do this.
Sorry if this has already been addressed but I couldn't find similar question on SO
Here is my example.
x <- runif(20)
a <- as.data.frame(x)
for (i in 1:100){
d <- x + i
a <- cbind(a, d)
}
c <- 1
for (i in 1:100){
c[i] <- paste0("colum", i)
}
colnames(a) <- c("x", c)
预先感谢任何好的建议,以使此过程全部在一个循环内而不是2个循环内完成.
Thanks in advance for any good suggestions to make this process all within one loop instead of 2.
推荐答案
为什么不呢?
a[2:11] <- sapply(1:10, "+", a[[1]])
名称为:
names(a) <- c("x", paste0("column", 1:10))
这篇关于在for循环中的R中创建列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!