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()、across()、および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ごとに1行を取ることができます。
# 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))
しかし、これには中間変数が含まれ、エレガントではないと感じます。
あなたは次の方法でそれを行うことができます:
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を超える値の割合を計算します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加