R:在数据帧中每行计数NAs [英] R: count NAs per row in dataframe

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

问题描述

我有数据帧具有批次ID,每个批次执行六个测试的结果。数据如下所示:

  batch_id test1 test2 test3 test4 test5 test6 
001 0.121 NA 0.340 0.877 0.417 0.662
002 0.229 0.108 NA 0.638 NA 0.574

(在这个数据框中只有几百行每个batch_id一行)



我正在寻找一种方法来计算每个batch_id(每行)有多少个NAs。我觉得这样应该是最好的几行R代码,但我无法实际编码它。
任何想法?

解决方案

您可以在数据框中添加一个新列,其中包含数量 NA batch_id

  df $ na_count<  -  apply(df,1,function(x)sum(is.na(x)))


I've got dataframe that has batch ID and the results of six tests performed on each batch. The data looks like this:

batch_id  test1  test2  test3  test4  test5  test6
001       0.121     NA  0.340  0.877  0.417  0.662
002       0.229  0.108     NA  0.638     NA  0.574

(there are a few hundred rows in this dataframe, only one row per batch_id)

I'm looking for a way to count how many NAs there are for each batch_id (for each row). I feel like this should be do-able with a few lines of R code at the most, but I'm having trouble actually coding it. Any ideas?

解决方案

You could add a new column to your data frame containing the number of NA values per batch_id:

df$na_count <- apply(df, 1, function(x) sum(is.na(x)))

这篇关于R:在数据帧中每行计数NAs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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