nFrain nFrain - 2 years ago 186
R Question

Turning data frame observations into list of lists

I have a data frame in R with three columns.


  1. lhs

  2. rhs

  3. conviction




example <- data.frame(lhs=c('phones', 'phones', 'phones',
'shoes', 'shoes', 'shoes'),
rhs=c('chargers', 'headphones', 'shoes',
'shirts', 'pants', 'socks'),
conviction=c(1.376, 1.259, 1.087,
1.295, 1.083, 0.978))



Here's a look at the output.

output

What I want to be able to do is turn this into a data frame with one column per item in lhs and a list of lists as the second column with the format [[rhs, conviction],[rhs,conviction]]

Something like this:

enter image description here

The end goal of all of this is to have a nested JSON file.

Final JSON should resemble this:

enter image description here

Thanks for any help.

Answer Source

You can use tidyverse to nest part of the data frame. This will still leave you with a nested tibble column. To convert this column to a list, you can use map and lapply like so

library(tidyverse)
ans <- example %>%
          nest(-lhs) %>%
          mutate(data = map(data, ~lapply(1:nrow(.x), function(i) .x[i,]))) %>%
          rename(rhs = data)

Here's what the rhs column looks like

ans$rhs
# [[1]]
# [[1]][[1]]
# # A tibble: 1 x 2
       # rhs conviction
    # <fctr>      <dbl>
# 1 chargers      1.376

# [[1]][[2]]
# # A tibble: 1 x 2
         # rhs conviction
      # <fctr>      <dbl>
# 1 headphones      1.259

# [[1]][[3]]
# # A tibble: 1 x 2
     # rhs conviction
  # <fctr>      <dbl>
# 1  shoes      1.087


# [[2]]
# [[2]][[1]]
# # A tibble: 1 x 2
     # rhs conviction
  # <fctr>      <dbl>
# 1 shirts      1.295

# [[2]][[2]]
# # A tibble: 1 x 2
     # rhs conviction
  # <fctr>      <dbl>
# 1  pants      1.083

# [[2]][[3]]
# # A tibble: 1 x 2
     # rhs conviction
  # <fctr>      <dbl>
# 1  socks      0.978
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download