Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

datatable - Count number of non-NA values for every column in a dataframe

I have a big dataset that contains a lot of NAs and some non-Na values. At the moment I count my non-NA values for each column like this:

 attach(df)
 1000 - (sum(is.na(X1)))
 1000 - (sum(is.na(X2)))
 1000 - (sum(is.na(X3)))
 1000 - (sum(is.na(X4)))
 1000 - (sum(is.na(X5)))
 ...
 detach(df)

So my overall length of my observations - the sum of my NA values.

Is there a faster way which uses less code lines and typing effort and gives me fast overview of all the columns and numbers of non-NA values?

Like a for loop or something?

I am looking for something like this:

  X1     Amount of Non-Na-Values
  X2     ...
  X3     ...
  X4
  X5
  X6  

Thank you :)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can also call is.na on the entire data frame (implicitly coercing to a logical matrix) and call colSums on the inverted response:

# make sample data
set.seed(47)
df <- as.data.frame(matrix(sample(c(0:1, NA), 100*5, TRUE), 100))

str(df)
#> 'data.frame':    100 obs. of  5 variables:
#>  $ V1: int  NA 1 NA NA 1 NA 1 1 1 NA ...
#>  $ V2: int  NA NA NA 1 NA 1 0 1 0 NA ...
#>  $ V3: int  1 1 0 1 1 NA NA 1 NA NA ...
#>  $ V4: int  NA 0 NA 0 0 NA 1 1 NA NA ...
#>  $ V5: int  NA NA NA 0 0 0 0 0 NA NA ...

colSums(!is.na(df))
#> V1 V2 V3 V4 V5 
#> 69 55 62 60 70

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...