[英]Count the number of NAs in multiple columns after grouping a dataframe in R
我有一個數據框df
,它是一個日期Date
、一個區域Region
和一個標識符ID
,然后是列中的一系列 12 個變量(例如V1 V2
...):
col1 <- as.Date(c("01/01/01","01/02/01","01/03/01","01/01/01","01/02/01","01/03/01"))
col2 <- c(1,1,1,2,2,2)
col3 <- c(8,NA,NA,4,3,5)
col4 <- c(NA,NA,NA,5,3,NA)
df <- data.frame(col1,col2,col3,col4)
colnames(df) <-c("Date", "ID", "V1", "V2")
df
Date Region ID V1 V2
1 2022-01-01 R1 1 8 NA
2 2022-01-02 R1 1 NA NA
3 2022-01-03 R1 1 NA NA
4 2022-01-01 R1 2 4 5
5 2022-01-02 R1 2 3 3
6 2022-01-03 R1 2 5 NA
本質上,我想創建另一個數據框來計算每個變量的 NA 數量,按ID
和Region
分組(可以忽略日期)。 我設法為一個變量獲得了它,但在添加第二個到第十二個時遇到了麻煩:
data.check <- as.data.frame(df %>% group_by(Region,ID) %>% summarise(sum(is.na(V1))))
data.check
Region ID sum(is.na(V1))
1 R1 1 2
2 R1 2 0
我嘗試了一些通常用於添加列的不同公式和技術,但它們不包含行分組。 以下是我嘗試的一些其他方法:
#Successful for Variable 1
data.check <- as.data.frame(df %>% group_by(Region,ID) %>% summarise(sum(is.na(V1))))
#Tried adding further piping for the second variable - unsuccessful
data.check <- as.data.frame(df %>% group_by(Region,ID) %>% summarise(sum(is.na(V1))) %>% group_by(Region,ID) %>% summarise(sum(is.na(V2))))
#tried adding the piping to a second variable column - unsuccessful
data.check <- as.data.frame(df %>% group_by(Region,ID) %>% summarise(sum(is.na(V1))))
data.check$V2 <- as.data.frame(data.check %>% group_by(Region,ID) %>% summarise(sum(is.na(df$V2))))
#tried only adding the sum of NA but it does not group by row "ID and Region" values and adds the entire column total
data.check$V2 <- sum(is.na(df$V2))
有誰知道我如何添加額外的列,計算每個 ID 的每個變量中的 NA 數量? 抱歉,如果我缺少一個簡單的方法,我對 R 還是很陌生。 提前感謝您的投入!
我真的很喜歡這個叫做collapse的庫
這是如何在該庫中執行此操作的示例。 如果您需要 go 回 dplyr,它可以與 dplyr 鏈接。
library(collapse)
df |>
fgroup_by(ID) |>
dapply(is.na) |>
fsum() |>
ungroup()
ID Date V1 V2
1 1 0 2 3
2 2 0 0 1
在 dplyr 中,跨 function 允許您指定列,如果您將其留空,就像我一樣,只留下一個逗號,它總結了所有內容
df |>
group_by(ID) |>
summarise(across(, ~ sum(is.na(.x))), .groups = "drop")
我提出兩種方法:
使用 dplyr:
df %>%
group_by(Region,ID) %>%
summarise_each(list(na_count = ~sum(is.na(.))))
或 data.table:
library(data.table)
setDT(df)[, lapply(.SD, function(x) sum(is.na(x))), by = .(Region, ID)]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.