Emily Jones
Emily Jones

Reputation: 45

How to assign something in a for loop?

Do you know how to assign these in a loop so it's less exhaustive?

number1 <- as.data.frame(do.call(cbind, my_list[1]))
number2 <- as.data.frame(do.call(cbind, my_list[2]))
number3 <- as.data.frame(do.call(cbind, my_list[3]))
number4 <- as.data.frame(do.call(cbind, my_list[4]))
number5 <- as.data.frame(do.call(cbind, my_list[5]))

I have tried:

for (i in 1:5) {
(number(i) <- as.data.frame(do.call(cbind, my_list[(i)])))
}

which doesn't work.

Any ideas?

Upvotes: 0

Views: 45

Answers (2)

Afshin
Afshin

Reputation: 133

You can use assign() function to do that. Please use the following example to get the idea and edit your code:

for (i in 1:5) {
  m <- data.frame(x=rnorm(10), y=rnorm(10))
  assign(paste0('number',i), m)
}
number1
number2
number3
number4
number5 

Best of Luck.

Upvotes: 1

jpsmith
jpsmith

Reputation: 17185

If you want to extract all the elements of a list in a data frame, you can use assign:

# Example list with 5 elements
my_list <- list(1:5, 1:5, 1:5, 1:5, 1:5)

for(xx in seq_along(my_list)){
  assign(paste0("number", xx), as.data.frame(do.call(cbind, my_list[xx])))
}

This will create 5 data frames in your global environment named number1, number2, ..., number5

Upvotes: 0

Related Questions