我正在尝试将ntile
应用到一些嵌套的小对象上,但似乎无法正常工作。
您能看到我要去哪里了吗?
data(iris)
iris %>%
group_by(Species) %>%
mutate(quintile = ntile(Petal.Length, 5)) # This works
nested_iris <- iris %>%
as_tibble() %>%
group_by(Species) %>%
nest(.key = "data") %>%
mutate(quintile = map(data, ~ntile(.x, Petal.Length, 5))) #This doesn`t work
最佳答案
将ntile
放在mutate
调用内,并更新“数据”以在其中创建新列。最小化存储结构可能更好
library(tidyverse)
o1 <- iris %>%
as_tibble() %>%
group_by(Species) %>%
nest(.key = "data") %>%
mutate(data = map(data, ~
.x %>%
mutate(quintile = ntile(Petal.Length, 5))))
# A tibble: 3 x 2
# Species data
# <fct> <list>
#1 setosa <tibble [50 × 5]>
#2 versicolor <tibble [50 × 5]>
#3 virginica <tibble [50 × 5]>
注意:假设OP需要所有带有附加“五分位数”的列。
然后,我们
unnest
o1 %>%
unnest
# A tibble: 150 x 6
# Species Sepal.Length Sepal.Width Petal.Length Petal.Width quintile
# <fct> <dbl> <dbl> <dbl> <dbl> <int>
# 1 setosa 5.1 3.5 1.4 0.2 2
# 2 setosa 4.9 3 1.4 0.2 2
# 3 setosa 4.7 3.2 1.3 0.2 1
# 4 setosa 4.6 3.1 1.5 0.2 3
# 5 setosa 5 3.6 1.4 0.2 2
# 6 setosa 5.4 3.9 1.7 0.4 5
# 7 setosa 4.6 3.4 1.4 0.3 2
# 8 setosa 5 3.4 1.5 0.2 3
# 9 setosa 4.4 2.9 1.4 0.2 2
#10 setosa 4.9 3.1 1.5 0.1 3
# … with 140 more rows