3

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.

2
  • 1
    For one thing, you can remove the second for loop completely. paste0("colum", 1:100) gives the same result. Commented Apr 1, 2015 at 20:58
  • Oh yes. thanks for that. I'm slightly editing the questions then. Commented Apr 1, 2015 at 21:00

3 Answers 3

2

Why not:

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

The names would be:

names(a) <- c("x", paste0("column", 1:10))
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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.

2 Comments

how can I take care of assigning only single rows in that context? For instance, when I create the different columns and their names in each loop I would like to assign different numbers to the certain rows of each column.
You are using eval(parse()) as a work around for the non-standard evaluation of $. That is just bad advice. Instead you should use [[. I suggest reading help("$") which mentions this as the recommended approach for passing element names programmatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.