Dominik
Dominik

Reputation: 792

how to nest a column into itself in tidyverse

library(tidyverse)

why does this produce a list column 'am':

mtcars %>%
group_by(cyl) %>%
mutate(am=list(mtcars[,'am']))

but not:

mtcars %>%
group_by(cyl) %>%
nest() %>%
mutate(am=list(mtcars[,'am']))

Error: not compatible with STRSXP

I realize this is a bit of a contrived example, but it's relevant to what I'm working on. Does mutate not scope outside its environment?

Upvotes: 0

Views: 1050

Answers (1)

alistaire
alistaire

Reputation: 43334

mtcars %>% group_by(cyl) %>% nest()

## # A tibble: 3 × 2
##     cyl               data
##   <dbl>             <list>
## 1     6  <tibble [7 × 10]>
## 2     4 <tibble [11 × 10]>
## 3     8 <tibble [14 × 10]>

has three rows, so any column you need has to have three elements, as well.

If you want the full am column for each row, you can either mutate rowwise, which will evaluate the mutate call separately for each row,

mtcars %>% group_by(cyl) %>% nest() %>% rowwise() %>% mutate(am = list(mtcars$am))

## Source: local data frame [3 x 3]
## Groups: <by row>
## 
## # A tibble: 3 × 3
##     cyl               data         am
##   <dbl>             <list>     <list>
## 1     6  <tibble [7 × 10]> <dbl [32]>
## 2     4 <tibble [11 × 10]> <dbl [32]>
## 3     8 <tibble [14 × 10]> <dbl [32]>

or without rowwise, just repeat the desired list for each row:

mtcars %>% group_by(cyl) %>% nest() %>% mutate(am = rep(list(mtcars$am), n()))

## # A tibble: 3 × 3
##     cyl               data         am
##   <dbl>             <list>     <list>
## 1     6  <tibble [7 × 10]> <dbl [32]>
## 2     4 <tibble [11 × 10]> <dbl [32]>
## 3     8 <tibble [14 × 10]> <dbl [32]>

Upvotes: 2

Related Questions