gpt4 book ai didi

r - 使用 dplyr 根据分组变量计算列 NA

转载 作者:行者123 更新时间:2023-12-04 12:14:10 24 4
gpt4 key购买 nike

虽然我怀疑之前没有发布过,但我找不到任何类似的问题。我的问题与 Calculate using dplyr, percentage of NA'S in each column .


在每个受试者有多个观察值的数据集中,不仅可以计算缺失数据条目的总数(即每列的总 NA),还可以计算有多少受试者缺失数据某种。

例如,在数据集 db 中(见下文)item_1 缺少 2 个主题,item_2 缺少 1 个主题。

Edit 1: What I am interested in is how many subjects have (any) missing value per item. Even if in item_2 there are two missing observations for subject number 1, this should be counted as 1 since it is still the same subject.

library("dplyr")

db <- data.frame(
subject = c(1, 1, 1, 2),
item_1 = c(NA, 2, 3, NA),
item_2 = c(1, NA, NA, 4)
)
db
#> subject item_1 item_2
#> 1 1 NA 1
#> 2 1 2 NA
#> 3 1 3 NA
#> 4 2 NA 4

到目前为止,我的方法是将所有单个计算cbind 到一个新的data.frame 中,但这很快就会变得困惑(有更多的列)并且肯定没有很好地编码。

Edit 1: However, this shows the desired values, as item_1 is missing for two subjects (1 and 2) and item_2 is only missing for 1 subject (subject 2).

cbind(
db %>%
filter(is.na(item_1)) %>%
summarise(na_item_1 = n_distinct(subject)),
db %>%
filter(is.na(item_2)) %>%
summarise(na_item_2 = n_distinct(subject))
)
#> na_item_1 na_item_2
#> 1 2 1

问题:dplyr 中是否有计算这个的方法?

理想情况下,我还想在某处添加缺失的比例(如下例所示):

data.frame(
type = c("n", "proportion"),
na_item_1 = c(2, 1.0),
na_item_2 = c(1, 0.5)
)
#> type na_item_1 na_item_2
#> 1 n 2.0 1.0
#> 2 proportion 1.0 0.5

reprex package 创建于 2019-04-16 (v0.2.1)

提前致谢!

最佳答案

另一个dplyr版本是第一个group_by subject找出有 any 的组NA值,然后 group_by列并计算 NA 的总值s n并将其除以 subject 的总唯一值得到prop .

library(dplyr)
library(tidyr)

db %>%
group_by(subject) %>%
summarise_all(~any(is.na(.))) %>%
ungroup() %>%
select(-subject) %>%
gather() %>%
group_by(key) %>%
summarise(n = sum(value),
prop = n/n_distinct(db$subject))

# key n prop
# <chr> <int> <dbl>
#1 item_1 2 1
#2 item_2 1 0.5

关于r - 使用 dplyr 根据分组变量计算列 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55708069/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com