在R中使用nest()后的列总和

时间:2018-08-01 10:41:06

标签: r dplyr purrr

我正在使用nest()函数使用长数据集创建多个模型。嵌套后,我需要找到已嵌套的列之一的总和,然后将其另存为嵌套级别的变异列。以下是使用虹膜数据集的类似示例。

library(tidyverse)

df <- iris %>%
    nest(-Species) %>%
    mutate(Total.Sepal.Length = map_dbl(data$Sepal.Length, sum, na.rm = TRUE))

出现以下错误:

Error in mutate_impl(.data, dots) : 
  Column `Total.Sepal.Length` must be length 3 (the number of rows) or one, not 0

1 个答案:

答案 0 :(得分:4)

这是一种实现方法:

library(dplyr)
library(purrr)

df <- iris %>%
    nest(-Species) %>%
    mutate(Total.Sepal.Length = map_dbl(data, ~sum(.$Sepal.Length, na.rm = TRUE)))

这是新列的外观:

# > df %>% select(-data)
#      Species Total.Sepal.Length
# 1     setosa              250.3
# 2 versicolor              296.8
# 3  virginica              329.4

要验证:

# > iris %>% group_by(Species) %>% summarise(sum(Sepal.Length))
# # A tibble: 3 x 2
#   Species    `sum(Sepal.Length)`
#   <fct>                    <dbl>
# 1 setosa                    250.
# 2 versicolor                297.
# 3 virginica                 329.