将Ntile应用于嵌套的小对象 [英] Applying ntile over nested tibbles

查看:33
本文介绍了将Ntile应用于嵌套的小对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 ntile 应用于一些嵌套的小块,但似乎无法正常工作。

I am trying to apply ntile over some nested tibbles but I cannot seem to get it working.

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 调用中,并将数据更新为在其中创建一个新列。最好使存储结构最小化

Place the ntile inside a mutate call and update the 'data' to create a new column inside it. It may be better to minimize the storage structure

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需要所有带有五分位数的列。

NOTE: Assuming that the OP need all the columns with the additional 'quintile'.

然后,我们 unstest

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

这篇关于将Ntile应用于嵌套的小对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆