简体   繁体   English

如何在tidyverse中将列嵌套到自身中

[英]how to nest a column into itself in tidyverse

library(tidyverse)

why does this produce a list column 'am': 为什么会产生列表列“ 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 错误:与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? 突变不会超出其环境范围吗?

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, 如果您希望每行都包含完整的am列,则可以按行进行突变,这将分别评估每行的mutate调用,

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: 或不rowwise ,只需为每行重复所需的列表:

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]>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM