Home > database >  How to count columns with values
How to count columns with values

Time:10-30

In my data I have 6 columns with values. Some of the participants have NA's and others have some values in there. Now I want to count 1 for each participant if they have a value in there and 0 if they have nothing, so an NA, in there. It doesnt matter which values are in the columns, just if there are values. How would I do that? Would that be possible with an ifelse function?

for example

2 4 6 8 10 12 -> 1
NA NA NA NA NA NA -> 0
1 3 5 7 9 11 -> 1

CodePudding user response:

df <- data.frame(matrix(data=rep.int(c(1, 2, NA), 12), ncol=6))

df$test_not_na <- apply(df, 1, FUN=function(x){as.integer(!any(is.na(x)))})

df

#   X1 X2 X3 X4 X5 X6 test_not_na
# 1  1  1  1  1  1  1       1
# 2  2  2  2  2  2  2       1
# 3 NA NA NA NA NA NA       0
# 4  1  1  1  1  1  1       1
# 5  2  2  2  2  2  2       1
# 6 NA NA NA NA NA NA       0
  •  Tags:  
  • r
  • Related