首页 > 解决方案 > 如何使用汇总来使用仅对其中一列进行的计算从多列中获取数据?

问题描述

我有关于新生儿出生第一年体重测量的数据:

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))

谢谢您的帮助!

标签: r

解决方案


也许有一个更优雅的解决方案,但这有效

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 日创建


推荐阅读