r - 如何使用 dplyr 访问/选择嵌套数据框列
问题描述
我有以下数据框:
library(tidyverse)
iris %>%
dplyr::select(Species, Petal.Width) %>%
as_tibble()
然后我通过以下代码行分组Species
以获取mean_se :
df <- iris %>%
dplyr::select(Species, Petal.Width) %>%
as_tibble() %>%
group_by(Species) %>%
mutate(ms = mean_se(Petal.Width))
它看起来像这样:
df
# A tibble: 150 x 3
# Groups: Species [3]
Species Petal.Width ms$y $ymin $ymax
<fct> <dbl> <dbl> <dbl> <dbl>
1 setosa 0.2 0.246 0.231 0.261
2 setosa 0.2 0.246 0.231 0.261
3 setosa 0.2 0.246 0.231 0.261
4 setosa 0.2 0.246 0.231 0.261
5 setosa 0.2 0.246 0.231 0.261
6 setosa 0.4 0.246 0.231 0.261
7 setosa 0.3 0.246 0.231 0.261
8 setosa 0.2 0.246 0.231 0.261
9 setosa 0.2 0.246 0.231 0.261
10 setosa 0.1 0.246 0.231 0.261
但是,当我想选择ms$y
和$ymax
列时,像这样
> df %>% dplyr::select(Species, ms$y, $ymax)
Error: unexpected '$' in "df %>% dplyr::select(Species, ms$y, $"
它失败。有什么办法呢?
解决方案
它被存储为嵌套数据框。您可以将其转换为普通数据框:
library(tidyverse)
iris %>%
select(Species, Petal.Width) %>%
as_tibble() %>%
group_by(Species) %>%
mutate(ms = mean_se(Petal.Width)) %>%
ungroup -> tmp
df <- bind_cols(tmp %>% select(-ms), tmp$ms)
df
# A tibble: 150 x 5
# Species Petal.Width y ymin ymax
# <fct> <dbl> <dbl> <dbl> <dbl>
# 1 setosa 0.2 0.246 0.231 0.261
# 2 setosa 0.2 0.246 0.231 0.261
# 3 setosa 0.2 0.246 0.231 0.261
# 4 setosa 0.2 0.246 0.231 0.261
# 5 setosa 0.2 0.246 0.231 0.261
# 6 setosa 0.4 0.246 0.231 0.261
# 7 setosa 0.3 0.246 0.231 0.261
# 8 setosa 0.2 0.246 0.231 0.261
# 9 setosa 0.2 0.246 0.231 0.261
#10 setosa 0.1 0.246 0.231 0.261
# … with 140 more rows
选择您需要的列。
df %>% select(Species, y, ymax)
# A tibble: 150 x 3
# Species y ymax
# <fct> <dbl> <dbl>
# 1 setosa 0.246 0.261
# 2 setosa 0.246 0.261
# 3 setosa 0.246 0.261
# 4 setosa 0.246 0.261
# 5 setosa 0.246 0.261
# 6 setosa 0.246 0.261
# 7 setosa 0.246 0.261
# 8 setosa 0.246 0.261
# 9 setosa 0.246 0.261
#10 setosa 0.246 0.261
# … with 140 more rows
不创建临时变量的另一种方法tmp
是:
iris %>%
select(Species, Petal.Width) %>%
as_tibble() %>%
group_by(Species) %>%
mutate(ms = list(mean_se(Petal.Width))) %>%
unnest(ms) %>%
ungroup
推荐阅读
- php - php 中定期付款的 PayPal 订阅
- dart - Is there a function in dart to remove substring with pattern?
- python - How to use the same layer/model twice in one model in Keras?
- react-native - 如何选择文本文件并将文件内容读取到字符串 React Native
- oracle - 页面加载期间 OAF 中的问题
- google-apps-script - Gmail 插件将参数传递给卡片操作触发的功能
- r - 在 3.5.1 版本中安装 quantstrat
- javascript - How to change color of row that contains different value using Angular 7?
- mysql - Mysql按链接表中的行顺序查询列
- swift - swift中GIF的持续时间