首页 > 解决方案 > 在 R 中使用 nest() 后的列总和

问题描述

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

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

标签: rdplyrpurrr

解决方案


这是一种方法:

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.

推荐阅读