Gabriel
Gabriel

Reputation: 81

Count values per rows in a data frame R

I know, there is other questions like this one but none of them answer my specific problem.

On my data frame, I need to count the number of values in each rows between cols 3 and 8.

I want a simple NB.VAL like in Excel..

base_graphs$NB <- rowSums(!is.na(base_graphs)) # with this code, I count all values except NAs but I can't select specific columns

How to create this new column "NB" on my data frame "base_graphs" ?

Upvotes: 2

Views: 1101

Answers (2)

Cole
Cole

Reputation: 11255

You were really close:

base_graphs$NB <- rowSums(!is.na(base_graphs[, 3:8]))

The [, 3:8] subsets and selects columns 3 through 8.

Upvotes: 3

dash2
dash2

Reputation: 2262

apply can apply a function to each row of a data frame. Try:

base_graphs$NB <- apply(base_graphs[3:8], 1, function (x) sum(is.na(x)))

Upvotes: 0

Related Questions