[英]How can I sum the totals of NA values in a data.frame or tibble column in R and group them by Month and Year
So here is a sample of my Data所以这是我的数据样本
year <- c(1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,
1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,
1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,
1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,
1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,
1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980 ,1980)
month <- c(1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1
,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,1 ,2
,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2
,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2 ,2)
Q <- c(NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA
,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,0.3 ,0.3 ,0.28
,0.26 ,0.26 ,0.25 ,0.25 ,0.24 ,0.24 ,0.24 ,0.24 ,0.23 ,0.23 ,NA ,NA
,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA ,NA)
I combined them into a dataframe called Flow我将它们组合成一个名为 Flow 的 dataframe
Flow <- data.frame(year,month,Q)
I can sum or count the number of missing or NA values in my Q column.我可以总结或计算我的 Q 列中缺失或 NA 值的数量。
sum(is.na(Flow$Q))
Now I am trying to calculate the sum of NA values in each month for the year and eventually each year.现在我正在尝试计算一年中每个月以及最终每年的 NA 值的总和。
This is where I'm stuck.这就是我卡住的地方。
group_by(Flow$year, Flow$month) %>%
sum(is.na(Flow$Q)
With group by, we can use summarise
.使用 group by,我们可以使用
summarise
。 Also, we don't need the Flow$
inside the group_by
此外,我们不需要
group_by
中的Flow$
library(dplyr)
Flow %>%
group_by(year, month) %>%
summarise(Nas = sum(is.na(Q)))
# A tibble: 2 x 3
# Groups: year [1]
# year month Nas
# <dbl> <dbl> <int>
#1 1980 1 28
#2 1980 2 19
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.