Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

data.frame rows to list named elements

Tags:

r

I have a list of mixed types, vector and data frames of 2 columns.

> my.list
$a
[1] 1

$df1
  key value
1   b     2
2   c     3

$df2
  key value
1   d     4
2   e     5

I would like to end up with a list of vectors only, each data frame row would become a list element with column value as value and column key as element name.

So the result in this example would be :

$a
[1] 1

$b
[1] 2

$c
[1] 3

$d
[1] 4

$e
[1] 5

Actually here is how I achieve this :

my.list <- list(a = 1, 
                df1 = data.frame(key = c("b", "c"), value = 2:3), 
                df2 = data.frame(key = c("d", "e"), value = 4:5))

unlist(lapply(seq_along(my.list), function(i) {
  if (is.data.frame(my.list[[i]])) {
    with(my.list[[i]], as.list(setNames(value, key), all.names = TRUE))
  } else {
    setNames(my.list[i], names(my.list[i]))
  }
}), recursive = FALSE)

But I don't realy like this solution. Do you have smarter ideas to achieve this please ? Thanks

like image 469
Julien Navarre Avatar asked Nov 27 '25 00:11

Julien Navarre


1 Answers

You can do it in two steps base R:

x = do.call(rbind, Filter(is.data.frame, my.list))

c(Filter(Negate(is.data.frame), my.list), as.list(setNames(x$value, x$key)))

$a
[1] 1

$b
[1] 2

$c
[1] 3

$d
[1] 4

$e
[1] 5
like image 171
Colonel Beauvel Avatar answered Nov 29 '25 17:11

Colonel Beauvel