tfr950
tfr950

Reputation: 422

Creating a variable to count number of zero values across variables occurring in each observation- R

I am trying to figure out a way to do this in R and for the life of me can't figure it out. Let's say I have a df consisting of the following.

v1<- c(0, 0, 2, 0 1 3)
v2<- c(1, 0, 8, 1 ,0)
v3<- c(0, 1, 3, 0, 0)
v4<- c(0, 0, 0, 0, 0)
df<- data.frame(v1, v2,v3, v4)

I want to create a new variable, say num_zeros, that counts the number of 0s for each observation in v1 to v3. Is there a quick way to do this? Any help would be greatly appreciated!

Upvotes: 1

Views: 50

Answers (2)

akrun
akrun

Reputation: 887531

We can use rowSums on a logical matrix to get the count of 0 values and assign it to 'num_zeros' column

df$num_zeros <- rowSums(df[c('v1', 'v2', 'v3')] == 0)

Or another option is

df$num_zeros <- (df$v1 == 0) + (df$v2 == 0) + (df$v3 == 0)

NOTE: Both methods are efficient and are vectorized

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389155

We can use apply rowwise :

cols <- paste0('v', 1:3)
df$num_zeros <- apply(df[cols] == 0, 1, sum)

Or with lapply :

df$num_zeros <- Reduce(`+`, lapply(df[cols], `==`, 0))

Upvotes: 0

Related Questions