1

Is there an already existing method of assigning each of those data.frame objects to separate variables?

list(cyl4, cyl6, cyl8) <- split(mtcars, mtcars$cyl)

Error in list(x, y, z) <- split(mtcars, mtcars$cyl) : could not find function "list<-

wdkrnls
  • 4,548
  • 7
  • 36
  • 64
  • 3
    You can name the list elements i.e. `lst <- split(mtcars, mtcars$cyl); names(lst) <- paste0('dat', seq_along(lst))` and use `list2env(lst, envir=.GlobalEnv)` But, I would recommend to work with list instead of having multiple objects in the global environment – akrun Jul 14 '15 at 13:13
  • 1
    Do you really *need* them to be in their own variables? Why not use the output from split directly? – Dason Jul 14 '15 at 13:16
  • I couldn't believe I was the first person to ask this question. Further Googling turned up: http://stackoverflow.com/questions/7519790/assign-multiple-new-variables-in-a-single-line-in-r. That was an older post though. Maybe something better has appeared since then? – wdkrnls Jul 14 '15 at 13:21
  • @Dason: I'm trying to simulate a multi-step process in R, where I do care about intermediate values. – wdkrnls Jul 14 '15 at 13:24
  • 1
    @wdkrnls I never said get rid of the intermediate values. But why do they need to be variables and not elements of a list? – Dason Jul 14 '15 at 13:25
  • @Dason: I have names in mind for each of the values of the list and may need to iteratively mutate each to solve nonlinear relationships between each data frame. – wdkrnls Jul 14 '15 at 14:19
  • 1
    And why does that mean you can't use a list? – Roland Jul 14 '15 at 14:22
  • Sounds like a case of [the XY problem](http://mywiki.wooledge.org/XyProblem) (sort of) – Dason Jul 14 '15 at 14:33

1 Answers1

2

You can use the assign to assign a value to variable. The variable names are strings.

In the code below I've looped though the elements of the list and assigned names from the vector names.

l <- split(mtcars, mtcars$cyl)   

names <- c('cyl4', 'cyl6', 'cyl8')

for (i in 1:length(names)) assign(names[i], l[[i]])

Or the list2env function as pointed out by @Roland (and others). The attach function does something similar.

l <- split(mtcars, mtcars$cyl)   

names(l) <- c('cyl4', 'cyl6', 'cyl8')

list2env(l, envir = .GlobalEnv)

Or

attach(l)

Although, as others have pointed out. This might not be the best idea; it's easier to keep track of things inside lists. You can just access them as need be with $.

l$cyl4
Mhairi McNeill
  • 1,951
  • 11
  • 20