In R, I have a list-of-lists that prints like this:
> ll <- list(list('fname'='joe', 'lname'='smith'), list('fname'='sally', 'lname'='smith'))
> ll
[[1]]
[[1]]$fname
[1] "joe"
[[1]]$lname
[1] "smith"
[[2]]
[[2]]$fname
[1] "sally"
[[2]]$lname
[1] "smith"
But if I start with a dataframe (from a SQL query) and obtain a list-of-lists from the apply
family of functions, it looks like this:
> ll2 <- apply(df, 1, as.list)
> ll2
$`1`
$`1`$fname
[1] "joe"
$`1`$lname
[1] "smith"
$`2`
$`2`$fname
[1] "sally"
$`2`$lname
[1] "smith"
So I would like to understand (1) what does the different notation signify---especially since both ll
and ll2
seem to be a list-of-lists? (2) how can I convert ll2
(or better yet df
) into something like ll
?
For instance in this similar question every answer produces something like ll2
not ll
. For instance lapply(split(df, 1:nrow(df)), as.list)
still looks like ll2
.
The only answer I've found so far is to loop over df
and add a new item to a list as I go:
> ret <- list()
> ret[[1]] <- list('fname'='joe', 'lname'='smith')
> ret[[2]] <- list('fname'='sally', 'lname'='smith')
> ret
[[1]]
[[1]]$fname
[1] "joe"
[[1]]$lname
[1] "smith"
[[2]]
[[2]]$fname
[1] "sally"
[[2]]$lname
[1] "smith"
But I can see that R people frown on building lists in loops. So if you don't like that approach, what is a better one?