在 R 中使用 nest() 后的列总和
Sum of Column after using nest() in R
我正在使用 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
这里有一个方法:
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.
我正在使用 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
这里有一个方法:
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.