使用dplyr添加列数为NAs和R的平均值 [英] Add a column with count of NAs and Mean in R with dplyr

查看:133
本文介绍了使用dplyr添加列数为NAs和R的平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我需要添加另一个列,它显示了该行的所有其他列中的NAs计数,也显示了非NA值的平均值。
我认为可以在dplyr中完成。

 > df1<  -  data.frame(a = 1:5,b = c(1,2,NA,4,NA),c = c(NA,2,3,NA,NA))
> df1
abc
1 1 1 NA
2 2 2 2
3 3 NA 3
4 4 4 NA
5 5 NA NA

我想突破另一列,计算该行中的NAs数,另一列显示所有NON的平均值



请帮助。

解决方案

  library(dplyr)

count_na< - function(x)sum(is.na(x))

df1%> %
mutate(means = rowMeans(。,na.rm = T),
count_na = apply(。,1,count_na))


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

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.

Please assist.

解决方案

library(dplyr)

count_na <- function(x) sum(is.na(x))

df1 %>%
  mutate(means = rowMeans(., na.rm = T),
         count_na = apply(., 1, count_na))

这篇关于使用dplyr添加列数为NAs和R的平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆