首页 文章

列表中df中列的特定值的NA的总和

提问于
浏览
1

我需要在数据框列表中得到每月NA的总和 .
该列表包含许多长度不同的数据帧,如下所示:

date year month day hour rain temp rhum
1 1950-01-01 01:00:00 1950     1   1    1    0  5.1   93
2 1950-01-01 02:00:00 1950     1   1    2    0  6.1   91
3 1950-01-01 03:00:00 1950     1   1    3    0  6.0   92
4 1950-01-01 04:00:00 1950     1   1    4    0  6.1   92
5 1950-01-01 05:00:00 1950     1   1    5    0  6.6   92
6 1950-01-01 06:00:00 1950     1   1    6    0  7.2   92

输出应该是相同数量的数据帧的相同列表,每个变量的摘要行:

year month  rain temp rhum
1  1950     1     2    3    1
2  1950     1     0    0    3

这段代码给出了每列每列的总和:

lapply(all_st, function(x) sapply(x, function(z) sum(is.na(z))))

1 回答

  • 1

    我们可以使用 data.table . 循环遍历data.frames列表后,将'data.frame'转换为'data.table'( setDT(x) ),按'year','month'分组,在 .SDcols 中指定感兴趣的列,循环遍历这些列并获取NA元素的逻辑向量的 sum

    library(data.table)
    lapply(all_st, function(x) setDT(x)[, lapply(.SD, function(x) sum(is.na(x))), 
                               by = .(year, month), .SDcols = rain:rhum])
    

相关问题