简体   繁体   English

在for循环中在R中创建列

[英]Create columns in R within a for loop

I have a data frame in R and I would like to create new columns within a for loop. 我在R中有一个数据框,我想在for循环中创建新列。 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)

Thanks in advance for any good suggestions to make this process all within one loop instead of 2. 提前感谢任何好的建议,使这个过程全部在一个循环而不是2。

Why not: 为什么不:

a[2:11] <- sapply(1:10, "+", a[[1]])

The names would be: 名称将是:

names(a) <- c("x", paste0("column", 1:10))

In this case you can avoid both loops. 在这种情况下,您可以避免两个循环。 In R you should always try to use vectorised statements when possible. 在R中,您应该尽可能尝试使用向量化语句。 In this case you can do this using addition fairly easily, one way is 在这种情况下,你可以很容易地使用添加,一种方法

result <- matrix(x + rep(0:100, length(x)), ncol = 101, byrow = TRUE)
result <- as.data.frame(result)
names(result) <- c("x", paste0("column", 1:100))

You can also keep the matrix structure if you only want to store numbers. 如果您只想存储数字,也可以保留矩阵结构。 Also, you should avoid using cbind , rbind and other functions that increase the size of an object with each iteration in loops. 此外,您应该避免使用cbindrbind和其他函数,这些函数会在循环中每次迭代时增加对象的大小。 The R inferno is a good book to read. R inferno是一本很好读的书。

Perhaps what you are looking for is eval and parse , as such: 也许您正在寻找的是evalparse ,因此:

for (i in 1:100) {
    eval(parse(text = paste0('a$colum', i, ' <- whatever_you_want_your_column_to_contain'))
}

This will create named columns and their contents in a single statement. 这将在单个语句中创建命名列及其内容。

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

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