New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
cnjr2 opened this Issue Mar 24, 2016 · 1 comment

Comments

Projects
None yet
2 participants
@cnjr2

cnjr2 commented Mar 24, 2016

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>

@hadley hadley closed this in bae80df May 16, 2016

@hadley

This comment has been minimized.

Member

hadley commented May 16, 2016

Turned out to be way easier than I thought it would be!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment