Jack Dean
Jack Dean

Reputation: 163

How to count number of numeric values in a row

I have a data frame like this

df <- as.data.frame(read.table(text =
                    "Human_Gene_Name    Human    Mouse    Chicken    Worm
                  Gene_1    8.5    7.0    NA    5.0
                  Gene_2    5.5    NA    NA    NA", header  = T))

I need to count the number of numeric values in each row and then add an extra column to my data frame with that value. So for Gene_1 one it would be 3 and for Gene_2 it would be 1.

Upvotes: 0

Views: 860

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99331

Just take the row sums of the result from !is.na(df) with the first column removed.

rowSums(!is.na(df[-1]))
# [1] 3 1

Upvotes: 2

Related Questions