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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With