Emi*_*der 1 r count missing-data
我有一个如下所示的数据框
Id Date Col1 Col2 Col3 Col4
30 2012-03-31 A42.2 20.46 NA
36 1996-11-15 NA V73 55
96 2010-02-07 X48 Z16 13
40 2010-03-18 AD14 20.12 36
69 2012-02-21 22.45
11 2013-07-03 81 V017 TCG11
22 2001-06-01 67
83 2005-03-16 80.45 V22.15 46.52 X29.11
92 2012-02-12
34 2014-03-10 82.12 N72.22 V45.44
Run Code Online (Sandbox Code Playgroud)
我正在尝试计算每行中NA或空单元格的数量,最终预期输出如下
Id Date Col1 Col2 Col3 Col4 MissCount
30 2012-03-31 A42.2 20.46 NA 2
36 1996-11-15 NA V73 55 2
96 2010-02-07 X48 Z16 13 1
40 2010-03-18 AD14 20.12 36 1
69 2012-02-21 22.45 3
11 2013-07-03 81 V017 TCG11 1
22 2001-06-01 67 3
83 2005-03-16 80.45 V22.15 46.52 X29.11 0
92 2012-02-12 4
34 2014-03-10 82.12 N72.22 V45.44 1
Run Code Online (Sandbox Code Playgroud)
最后一列MissCount将存储NAs每行的单元格数或空单元格。任何帮助深表感谢。
单行
rowSums(is.na(df) | df == "")
Run Code Online (Sandbox Code Playgroud)
@DavidArenburg 在他的评论中给出的绝对是要走的路,假设您不介意检查数据框中的每一列。如果您真的只想 check Col1through Col4,那么使用apply函数可能更有意义。
apply(df, 1, function(x) {
sum(is.na(x[c("Col1", "Col2", "Col3", "Col4")])) +
sum(x[c("Col1", "Col2", "Col3", "Col4")] == "", na.rm=TRUE)
})
Run Code Online (Sandbox Code Playgroud)
编辑:缩短的代码
apply(df[c("Col1", "Col2", "Col3", "Col4")], 1, function(x) {
sum(is.na(x)) +
sum(x == "", na.rm=TRUE)
})
Run Code Online (Sandbox Code Playgroud)
或者如果数据列与示例数据完全一样:
apply(df[3:6], 1, function(x) {
sum(is.na(x)) +
sum(x == "", na.rm=TRUE)
})
Run Code Online (Sandbox Code Playgroud)