I have a dataframe obtained from a SQL query like so:
conn <- dbConnect(PostgreSQL(), user=...)
res <- dbGetQuery(conn, "SELECT fname, lname from users")
Now I want to convert it into a list-of-lists, as if I had done this:
> list(list('fname'='joe', 'lname'='smith'), list('fname'='sally', 'lname'='smith'))
[[1]]
[[1]]$fname
[1] "joe"
[[1]]$lname
[1] "smith"
[[2]]
[[2]]$fname
[1] "sally"
[[2]]$lname
[1] "smith"
I have tried a bunch of variants of apply
and lapply
, but nothing seems to be quite right. This is the closest, but it's still off:
> lapply(split(res, 1:nrow(res)), function(x) list('fname'=x['fname'], 'lname'=x['lname']))
$`1`
$`1`$fname
fname
1 Joe
$`1`$lname
lname
1 Smith
$`2`
$`2`$fname
fname
2 Sally
$`2`$lname
lname
2 Smith
What is the right way to get a list-of-lists from my dataframe?
Edit: I have tried all the solutions in this similar question but none of them produce my desired output. They give results like this:
$`1`
$`1`$fname
[1] "Joe"
not:
[[1]]
[[1]]$fname
[1] "joe"