将Ntile应用于嵌套的小对象

时间:2019-05-03 14:06:17

标签: r dataframe dplyr purrr

我正在尝试将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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

您需要在transmute内插入mutatemap

nested_iris <- iris %>%
  as_tibble() %>%
  group_by(Species) %>%
  nest(.key = "data") %>%
  mutate(quintile = map(data, ~transmute(.x, quantile = ntile(Petal.Length, 5))))

# A tibble: 3 x 3
  Species    data              quintile         
  <fct>      <list>            <list>           
1 setosa     <tibble [50 x 4]> <tibble [50 x 1]>
2 versicolor <tibble [50 x 4]> <tibble [50 x 1]>
3 virginica  <tibble [50 x 4]> <tibble [50 x 1]>