添加具有NA和均值计数的列 [英] Add a column with count of NAs and Mean
本文介绍了添加具有NA和均值计数的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,我需要向其添加另一列,以显示该行在所有其他列中的NA计数以及非NA值的平均值. 我认为可以在dplyr中完成.
I have a data frame and I need to add another column to it which shows the count of NAs in all the other columns for that row and also the mean of the non-NA values. I think it can be done in dplyr.
> df1 <- data.frame(a = 1:5, b = c(1,2,NA,4,NA), c = c(NA,2,3,NA,NA))
> df1
a b c
1 1 1 NA
2 2 2 2
3 3 NA 3
4 4 4 NA
5 5 NA NA
我想更改另一列,该列计算该行中NA的数量,而另一列则显示该行中所有NON-NA值的均值.
I want to mutate another column which counts the number of NAs in that row and another column which shows the mean of all the NON-NA values in that row.
推荐答案
library(dplyr)
count_na <- function(x) sum(is.na(x))
df1 %>%
mutate(means = rowMeans(., na.rm = T),
count_na = apply(., 1, count_na))
这篇关于添加具有NA和均值计数的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文