簡體   English   中英

有沒有一種方法可以計算出數據幀每一列中NA的百分比,而將df分為不同的組呢?

[英]Is there a way to calculate the percentage of NA's in each column of a dataframe, but with the df split into separate groups?

我正在尋找確定數據框各列中缺失值的比率,並按該數據框中的各個組進行划分。

我對R很陌生,所以到目前為止我還沒有取得太大的成功。 這是一個示例數據集,可以對其進行測試:

df <- data.frame(
  programme = c('A','B','B','A','B','C','C','C','C','A'),
  v1 = c(24,NA,NA,45,NA,23,22,23,45,23),
  v2 = c(NA,1,1,NA,0,1,1,1,1,NA),
  v3 = c(2,3,2,3,2,NA,NA,NA,NA,2))

我考慮過按組拆分數據框,然后為每列應用一個函數,但這似乎不起作用

per_missing <- data.frame()
df %>%
  group_by(programme)
  per_missing <- apply(df, 2, function(col)sum(is.na(col))/length(col))

理想情況下,該信息將被寫入一個新的數據框中,在此為每個組列出每列的丟失率值。 看起來像這樣:

res <- data.frame(
  variables = c('v1','v2','v3'),
  A = c(0.0, 1, 0.0),
  B = c(1, 0.0, 0.0),
  C = c(0.0, 0.0, 1)
)

  variables A B C
1        v1 0 1 0
2        v2 1 0 0
3        v3 0 0 1


在此先感謝您的幫助!

按“程序”分組,在其他列中獲取NA元素的meangather為“長”格式,然后spread回“寬”格式

library(tidyverse)
df %>% 
  group_by(programme) %>%
  summarise_all(funs(mean(is.na(.)))) %>% 
  gather(variables, val, -programme) %>% 
  spread(programme, val)
# A tibble: 3 x 4
#   variables     A     B     C
#   <chr>     <int> <int> <int>
#1 v1            0     1     0
#2 v2            1     0     0
#3 v3            0     0     1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM