Home > Mobile >  How to assign something in a for loop?
How to assign something in a for loop?

Time:11-18

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?

CodePudding user response:

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

CodePudding user response:

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

number1 <- data.frame()
number2 <- data.frame()
number3 <- data.frame()
number4 <- data.frame()
number5 <- data.frame()

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.

  • Related