Wolfgang
Wolfgang

Reputation: 3385

Turn multiple data frame columns into separate list elements

Suppose I have an unnamed list, where each element is a data frame with one or more columns. For some of the list elements (those for which conv is TRUE), I want to turn each column into a separate list element (so a data frame with just one column). An example:

x <- list(data.frame(a=c(1,3,4)),
          data.frame(v=c("B","C","A"), w=c(12,14,17), h=c(1,2,3)),
          data.frame(m=c(2.2,4.1,5.0)),
          data.frame(h=c(4,1,2), u=c(9,7,2)))
conv <- c(FALSE, TRUE, FALSE, FALSE)
x

From this, I want to go to:

x <- list(x[[1]], x[[2]][1], x[[2]][2], x[[2]][3], x[[3]], x[[4]])
x

I can do this with awkward looping, but would like something more efficient. Also, I would prefer a solution that sticks to base package functionality.

Upvotes: 4

Views: 198

Answers (1)

BrodieG
BrodieG

Reputation: 52637

I believe this does what you want (note, credit to @DavidArenburg for using [ to pull out the columns):

unlist(recursive=FALSE, 
  mapply(
    function(item, exp) if(exp) lapply(seq(item), function(x) item[x]) else list(item),
    x,
    conv
) )

Here is the str output:

List of 6
 $ :'data.frame': 3 obs. of  1 variable:
  ..$ a: num [1:3] 1 3 4
 $ :'data.frame': 3 obs. of  1 variable:
  ..$ v: Factor w/ 3 levels "A","B","C": 2 3 1
 $ :'data.frame': 3 obs. of  1 variable:
  ..$ w: num [1:3] 12 14 17
 $ :'data.frame': 3 obs. of  1 variable:
  ..$ h: num [1:3] 1 2 3
 $ :'data.frame': 3 obs. of  1 variable:
  ..$ m: num [1:3] 2.2 4.1 5
 $ :'data.frame': 3 obs. of  2 variables:
  ..$ h: num [1:3] 4 1 2
  ..$ u: num [1:3] 9 7 2

Upvotes: 4

Related Questions