Franky
Franky

Reputation: 751

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. 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.

Upvotes: 3

Views: 13553

Answers (3)

IRTFM
IRTFM

Reputation: 263301

Why not:

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

The names would be:

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

Upvotes: 2

data paRty
data paRty

Reputation: 218

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.

Upvotes: 1

konvas
konvas

Reputation: 14346

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.

Upvotes: 1

Related Questions