Home > Blockchain >  Creating a New Data Frame For Each Element in a List
Creating a New Data Frame For Each Element in a List

Time:12-31

Suppose I have the following list "d":

library(combinat)
d = permn(c("a", "b", "c"))

This looks as follows:

[[1]]
[1] "a" "b" "c"

[[2]]
[1] "a" "c" "b"

[[3]]
[1] "c" "a" "b"

[[4]]
[1] "c" "b" "a"

[[5]]
[1] "b" "c" "a"

[[6]]
[1] "b" "a" "c"

Is it possible to convert each element into a new data frame?

This is what I am trying to do:

data_1  = data.frame(col1 = c("a", "b", "c"))
data_2  = data.frame(col1 = c("a", "c", "b"))
data_3  = data.frame(col1 = c("c", "a", "b"))
data_4  = data.frame(col1 = c("c", "b", "a"))
data_5  = data.frame(col1 = c("b", "c", "a"))
data_6  = data.frame(col1 = c("b", "a", "c"))

Can someone please show me how to do this?

Thanks!

CodePudding user response:

You could list2env into the .GlobalEnv after making data.frames and setNames.

lapply(d, \(x) data.frame(col1=x)) |>
  setNames(paste0('data', seq_along(d))) |>
  list2env(envir=.GlobalEnv)

data1
#   col1
# 1    a
# 2    b
# 3    c

R version < 4.1:

list2env(
  setNames(
    lapply(d, function(x) data.frame(col1=x)), 
    paste0('data', seq_along(d))),
  envir=.GlobalEnv)

CodePudding user response:

A tidyverse option:

library(tidyverse)

purrr::map(d, function(x)
  as.data.frame(x) %>% rename("col" = x)) %>%
  set_names(paste0('data_', seq_along(d))) %>%
  list2env(envir = .GlobalEnv)
  • Related