使用 purr:map 过滤和变异嵌套的鸢尾花数据集
filter and mutate nested iris dataset using purr:map
假设我有一个基于“物种”列的嵌套鸢尾花数据集,我如何将 purr::map 应用到这个嵌套数据上:
- 例如根据(Sepal.Length>5)过滤每个“物种”中的行
- 在每个“物种”中变异一个新列,它是 Sepal.Length 和 Petal.Length
的“总和”
??
谢谢!!
你或许可以试试这个 -
library(dplyr)
library(purrr)
iris %>%
nest(data = -Species) %>%
mutate(data = map(data, ~.x %>%
filter(Sepal.Length>5) %>%
mutate(sum = Sepal.Length + Petal.Length)))
# Species data
# <fct> <list>
#1 setosa <tibble [22 × 5]>
#2 versicolor <tibble [47 × 5]>
#3 virginica <tibble [49 × 5]>
你也可以试试这个。在许多使用 purrr::map()
的嵌套数据用例中,我们可以在其较新版本 (>1.0.0) 中仅取消 {dplyr}
。
library(dplyr) # version 1.0.6
iris %>%
nest_by(Species) %>%
mutate(data_new = list(
data %>%
filter(Sepal.Length > 5) %>%
mutate(sum = sum(Sepal.Length))
)) %>%
ungroup()
# # A tibble: 3 x 3
# Species data data_new
# <fct> <list<tibble[,4]>> <list>
# 1 setosa [50 x 4] <tibble [22 x 5]>
# 2 versicolor [50 x 4] <tibble [47 x 5]>
# 3 virginica [50 x 4] <tibble [49 x 5]>
假设我有一个基于“物种”列的嵌套鸢尾花数据集,我如何将 purr::map 应用到这个嵌套数据上:
- 例如根据(Sepal.Length>5)过滤每个“物种”中的行
- 在每个“物种”中变异一个新列,它是 Sepal.Length 和 Petal.Length 的“总和”
??
谢谢!!
你或许可以试试这个 -
library(dplyr)
library(purrr)
iris %>%
nest(data = -Species) %>%
mutate(data = map(data, ~.x %>%
filter(Sepal.Length>5) %>%
mutate(sum = Sepal.Length + Petal.Length)))
# Species data
# <fct> <list>
#1 setosa <tibble [22 × 5]>
#2 versicolor <tibble [47 × 5]>
#3 virginica <tibble [49 × 5]>
你也可以试试这个。在许多使用 purrr::map()
的嵌套数据用例中,我们可以在其较新版本 (>1.0.0) 中仅取消 {dplyr}
。
library(dplyr) # version 1.0.6
iris %>%
nest_by(Species) %>%
mutate(data_new = list(
data %>%
filter(Sepal.Length > 5) %>%
mutate(sum = sum(Sepal.Length))
)) %>%
ungroup()
# # A tibble: 3 x 3
# Species data data_new
# <fct> <list<tibble[,4]>> <list>
# 1 setosa [50 x 4] <tibble [22 x 5]>
# 2 versicolor [50 x 4] <tibble [47 x 5]>
# 3 virginica [50 x 4] <tibble [49 x 5]>