Create columns in R within a for loop

10,174

Solution 1

Why not:

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

The names would be:

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

Solution 2

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.

Solution 3

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.

Share:
10,174
Franky
Author by

Franky

enjoy developing with R

Updated on June 04, 2022

Comments

  • Franky
    Franky almost 2 years

    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.