计算数据帧中的非NA;得到答案作为向量 [英] Counting non NAs in a data frame; getting answer as a vector

查看:76
本文介绍了计算数据帧中的非NA;得到答案作为向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下R data.frame ZZZ:

( ZZZ <- structure(list(n = c(1, 2, NA), m = c(6, NA, NA), o = c(7, 8, 
8)), .Names = c("n", "m", "o"), row.names = c(NA, -3L), class = "data.frame") )

## not run
   n  m o
1  1  6 7
2  2 NA 8
3 NA NA 8

我想以向量的形式知道我有多少个非NA.我希望答案为:

I want to know, in the form of a vector, how many non-NAs I've got. I want the answer available to me as:

2, 1, 3

使用命令length(ZZZ)时,我得到3,这当然是 data.frame 中向量的数量,这是足够有价值的信息.

When I use the command length(ZZZ), I get 3, which of course is the number of vectors in the data.frame, a valuable enough piece of information.

我还有其他功能可以对此 data.frame 进行操作,并以矢量的形式给我答案,但是dang-it的长度却不是那样.

I have other functions that operate on this data.frame and give me answers in the form of vectors, but, dang-it, length doesn't operate like that.

推荐答案

尝试一下:

# define "demo" dataset
ZZZ <- data.frame(n=c(1,2,NA),m=c(6,NA,NA),o=c(7,8,8))
# apply the counting function per columns
apply(ZZZ, 2, function(x) length(which(!is.na(x))))

正在运行:

> apply(ZZZ, 2, function(x) length(which(!is.na(x))))
n m o 
2 1 3 

如果您确实坚持要返回向量,则可以使用as.vector,例如通过定义此功能:

If you really insist on returning a vector, you might use as.vector, e.g. by defining this function:

nonNAs <- function(x) {
    as.vector(apply(x, 2, function(x) length(which(!is.na(x)))))
    }

您只需运行nonNAs(ZZZ):

> nonNAs(ZZZ)
[1] 2 1 3

这篇关于计算数据帧中的非NA;得到答案作为向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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