Create columns in R within a for loop

两盒软妹~` 提交于 2020-01-05 10:11:28

问题


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)

Thanks in advance for any good suggestions to make this process all within one loop instead of 2.


回答1:


Why not:

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

The names would be:

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



回答2:


In this case you can avoid both loops. In R you should always try to use vectorised statements when possible. 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. The R inferno is a good book to read.




回答3:


Perhaps what you are looking for is eval and parse, as such:

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.



来源:https://stackoverflow.com/questions/29400650/create-columns-in-r-within-a-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!