Username
Username

Reputation: 3663

How do I count the number of cells for certain columns that have data?

I have a data frame called df that looks like this:

name score1 score2 score3
Joe     1      NA    3
Jane    NA     2     3

How do I make a TOTAL_NonEmpty column that counts the number of non-empty cells in score1, score2 and score3?

Upvotes: 0

Views: 49

Answers (1)

Raphael K
Raphael K

Reputation: 2353

In base R,

df$TOTAL_NonEmpty <- rowSums(!is.na(df))

## For specifically those columns:
df$TOTAL_NonEmpty <- rowSums(!is.na(df[, c('score1', 'score2', 'score3')]))

Should give you the count of non-missing values for each row.

Upvotes: 2

Related Questions