Skip to content

melt data.frames with non-atomic 'measure' columns #175

@cnjr2

Description

@cnjr2

Is it possible to gather() a data frame when it contains list elements?

library("dplyr")
library("tidyr")
library("purrr")

data <- data_frame(
    name = c("Alex", "Alex", "Alex", "Tim", "Tim", "Tim"),
    year = c(1990, 1991, 1992, 1990, 1991, 1992),
    height = c(160, 165, 170, 120, 134, 150),
    weight = c(50, 52, 53, 48, 48, 52)
)

models <- data %>%
    group_by(name) %>%
    nest() %>%
    mutate(
        lm = map(data, ~lm(year ~ height, data = .)),
        lm2 = map(data, ~lm(year ~ height + weight, data = .))
    )

models

This produces the following output:

   name           data      lm     lm2
  (chr)          (chr)   (chr)   (chr)
1  Alex <tbl_df [3,3]> <S3:lm> <S3:lm>
2   Tim <tbl_df [3,3]> <S3:lm> <S3:lm>

Now I would want to gather() this into a long format:

models %>% gather(variabe, value, -name, -data)

But I get:

Error: Can't melt data.frames with non-atomic 'measure' columns

I would like to end up with final data frame like this:

   name            data  variable    value
  (chr)           (chr)     (chr)    (chr)
1  Alex  <tbl_df [3,3]>        lm  <S3:lm>
2  Alex  <tbl_df [3,3]>       lm2  <S3:lm>
3   Tim  <tbl_df [3,3]>        lm  <S3:lm>
4   Tim  <tbl_df [3,3]>       lm2  <S3:lm>

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions