Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

r - Counting non NAs in a data frame; getting answer as a vector

Say I have the following 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

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

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
colSums(!is.na(x))

Vectorisation ftw.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...