汇总使用dplyr跨()函数

时间:2020-11-06 03:45:19

标签: r dplyr

我有一个ID变量应标识唯一观察值的数据。但是,某些ID会重复。我想通过按ID分组然后计算每个变量不一致响应的比例来了解哪些测量值在驱动此重复。

以下是我的意思的示例:

require(tidyverse)

df <- tibble(id = c(1,1,2,3,4,4,4),
             col1 = c('a','a','b','b','c','c','c'), # perfectly consistent
             col2 = c('a','b','b','b','c','c','c'), # id 1 is inconsistent - proportion inconsistent = 0.25
             col3 = c('a','a','b','b','a','b','c'), # id 4 is inconsistent - proportion inconsistent = 0.25
             col4 = c('a','b','b','b','b','b','c') # id 1 and 4 are inconsistent - proportion inconsistent = 0.5
             )

我可以按照以下方式使用group_by(),crossover()和n_distinct()来测试ID中的响应不一致:

# count the number of distinct responses for each id in each column
# if the value is equal to 1, it means that all responses were consistent
df <- df %>% 
  group_by(id) %>% 
  mutate(across(.cols = c(col1:col4), ~n_distinct(.), .names = '{.col}_distinct')) %>% 
  ungroup()

为简单起见,我现在可以为每个id占用一行:

# take one row for each test (so we aren't counting duplicates twice)
df <- distinct(df, across(c(id, contains('distinct'))))

现在,我想计算每个变量包含不一致响应的id的比例。我想做以下事情:

consistency <- df %>% 
  summarise(across(contains('distinct'), ~sum(.>1) / n(.)))

但是这给出了以下错误,我无法解释:

Error: Problem with `summarise()` input `..1`.
x unused argument (.)
ℹ Input `..1` is `across(contains("distinct"), ~sum(. > 1)/n(.))`.

我可以通过以下操作获得想要的答案:

# calculate consistency for each column by finding the number of distinct values greater 
# than 1 and dividing by total rows
# first get the number of distinct values
n_inconsistent <- df %>% 
  summarise(across(.cols = contains('distinct'), ~sum(.>1)))

# next get the number of rows
n_total <- nrow(df)

# calculate the proportion of tests that have more than one value for each column
consistency <- n_inconsistent %>% 
  mutate(across(contains('distinct'), ~./n_total))

但这涉及中间变量并且感觉不佳。

1 个答案:

答案 0 :(得分:2)

您可以通过以下方式进行操作:

library(dplyr)

df %>%
  group_by(id) %>%
  summarise(across(starts_with('col'), n_distinct)) %>%
  summarise(across(starts_with('col'), ~mean(. > 1), .names = '{col}_distinct'))

#  col1_distinct col2_distinct col3_distinct col4_distinct
#          <dbl>         <dbl>         <dbl>         <dbl>
#1             0          0.25          0.25           0.5

首先,我们计算id每列中唯一值的数量,然后计算每列中大于1的值的比例。