计算dplyr中每行的非NA数值的数量 [英] count the number of non-NA numeric values of each row in dplyr

查看:68
本文介绍了计算dplyr中每行的非NA数值的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个数据框df.

I create a dataframe df.

df <- data.frame (id = 1:10, 
    var1 = 10:19,
    var2 = sample(c(1:2,NA), 10, replace=T),
    var3 = sample(c(3:5, NA), 10, replace=T))

我需要的是一个新列var4,它计算每行(不包括id列)的非NA值的数量.因此,例如,如果某行类似于var1 = 19,var2 = 1,var3 = NA,则var4 = 2.我找不到在dplyr中执行此操作的好方法.像这样:

What I need is a new column var4, which count the number of non-NA values of each row (excluding the id column). So for example, if a row is like var1=19, var2=1, var3=NA, then var4=2. I could not find a good way to do this in dplyr. something like:

df %in% mutate(var4= ... )

如果有人能帮助我,我将感激不尽.

I appreciate if anyone can help me with that.

推荐答案

使用 select + is.na + rowSums select(.,-id)返回排除了 id 的原始数据帧(.),然后使用计数非NA值的数量rowSums(!is.na(...)):

Use select + is.na + rowSums, select(., -id) returns the original data frame (.) with id excluded, and then count number of non-NA values with rowSums(!is.na(...)):

df %>% mutate(var4 = rowSums(!is.na(select(., -id))))

#   id var1 var2 var3 var4
#1   1   10   NA    4    2
#2   2   11    1   NA    2
#3   3   12    2    5    3
#4   4   13    2   NA    2
#5   5   14    1   NA    2
#6   6   15    1   NA    2
#7   7   16    1    5    3
#8   8   17   NA    4    2
#9   9   18   NA    4    2
#10 10   19   NA   NA    1

这篇关于计算dplyr中每行的非NA数值的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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