添加一列包含 NA 和平均值的计数 [英] Add a column with count of NAs and Mean

查看:30
本文介绍了添加一列包含 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))

#### ANSWER FOR RADEK ####
elected_cols <- c('b', 'c')

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

这篇关于添加一列包含 NA 和平均值的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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