r - 在 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
解决方案
这是一种方法:
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.
推荐阅读
- java - 模块的循环引用
- json - 需要 JSON 中“dd-mm-yyyy”格式的日期
- python - Pytorch 3D 张量与 1D 张量的内积以生成 2D 张量
- asp.net-core - 如何在 ASP.NET Core 2 中本地化大文本
- java - 我如何使用 java 8 基于先前的组合在两个字符之间生成连接?
- java - 如何解决 java.lang.UnsatisfiedLinkError: java.awt.Toolkit.initIDs 异常?
- typescript - Importing declarations from another file with as little repetition as possible?
- amazon-cognito - 是否可以在不使用 Amazon Cognito 的情况下使用 AWS Amplify?
- java - E/BluetoothAdapter:蓝牙绑定器为空
- symfony - Symfony4正确处理参数配置设置的方法