r - 如何使用汇总来使用仅对其中一列进行的计算从多列中获取数据?
问题描述
我有关于新生儿出生第一年体重测量的数据:
Children <- data.frame(ID = c(1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4),
age_days = c(0,12,25,33,38,2,25,38,45,18,38,40,60,1,5,10,20),
weight = c(3.4,3.5,4.5,5.1,5.3,2.8,4.5,5.3,5.6,3.6,5.4,5.5,6.8,3.1,3.0,3.3,4.1))
我想创建一个表格,其中对于每个孩子 ID,我都有 2 周和 1 个月的测量值。由于大多数孩子在 2 周或 1 个月时没有测量,我想选择最接近我需要的年龄的测量。
我创建了新变量来计算与我需要的年龄测量的绝对距离:
Children <- mutate(Children, dis_2weeks = abs(14-age_days), dis_1month = abs(30-age_days))
现在我想创建一个表格,其中将为每个孩子提供与我指定的年龄最接近的测量数据(与所需年龄的距离和该测量的体重)。它看起来大概是这样的:
ID dis_2weeks weight_2weeks dis_1month weight_1month
1 1 2 3.5 3 5.1
2 2 11 4.5 5 4.5
3 3 4 3.6 8 5.4
4 4 4 3.3 10 4.1
我曾尝试使用 summarise 函数,但似乎找不到使用它获取权重的方法
Children %>% group_by(ID) %>% summarise(dis_2weeks = min(dis_2weeks), dis_1month = min(dis_1month))
谢谢您的帮助!
解决方案
也许有一个更优雅的解决方案,但这有效
library(tidyverse)
Children <- data.frame(ID = c(1,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4),
age_days = c(0,12,25,33,38,2,25,38,45,18,38,40,60,1,5,10,20),
weight = c(3.4,3.5,4.5,5.1,5.3,2.8,4.5,5.3,5.6,3.6,5.4,5.5,6.8,3.1,3.0,3.3,4.1))
Children <- mutate(Children, dis_2weeks = abs(14-age_days), dis_1month = abs(30-age_days))
# Find two-week and one-month weights for a single child
best_weights = function(df) {
ix_2weeks = which.min(df$dis_2weeks)
ix_1month = which.min(df$dis_1month)
tibble(dis_2weeks=df$dis_2weeks[ix_2weeks],
weight_2weeks = df$weight[ix_2weeks],
dis_1month=df$dis_1month[ix_1month],
weight_1month = df$weight[ix_1month]
)
}
Children %>% group_by(ID) %>%
nest() %>%
mutate(new_data = map(data, best_weights)) %>%
select(-data) %>%
unnest('new_data')
#> # A tibble: 4 x 5
#> # Groups: ID [4]
#> ID dis_2weeks weight_2weeks dis_1month weight_1month
#> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 1 2 3.5 3 5.1
#> 2 2 11 4.5 5 4.5
#> 3 3 4 3.6 8 5.4
#> 4 4 4 3.3 10 4.1
由reprex 包(v0.3.0)于 2020 年 1 月 14 日创建
推荐阅读
- java - 如何在 Spring Boot 中为 /error 页面返回自定义错误消息
- postgresql - 用于同时运行的查询的 Tempo 表抛出已存在错误
- c# - 警告 CS1998 此异步方法缺少“等待”运算符,正确的静音方法?
- javascript - 'setTimeout' javascript 函数不起作用的代码有什么问题?
- java - Hibernate使用多对多关系多次加载同一个实体并离开连接?
- powerbuilder - 我有一个带有一个 IN 参数和一个 OUT 参数的 Oracle 存储过程。我需要从 PowerBuilder 调用它
- flutter - Flutter 照片编辑应用调整
- reactjs - '}' 预期在 React 组件渲染方法中(使用 JSX)
- amazon-web-services - AWS SNS 主题访问策略不阻止用户订阅
- java - 错误原因:java.lang.ClassCastException: androidx.viewpager2.widget.ViewPager2 无法转换为 androidx.viewpager.widget.ViewPager