0

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"
Community
  • 1
  • 1
Paul A Jungwirth
  • 23,504
  • 14
  • 74
  • 93
  • Please see my edit for why this is not a duplicate. – Paul A Jungwirth Jun 13 '16 at 16:51
  • I think you just want to strip out the names in the higher levels of the list. If `names(myList[[1]])` is something like 1 2 3 4, then assign names to NULL. `sapply` and `vapply` have USE.NAMES arguments that you may set to FALSE. – lmo Jun 13 '16 at 17:01

0 Answers0