'Count the number of non empty columns in R [duplicate]
I want to add a column in a dataframe that adds up the number of non-empty values for each row. The total column shows the end result that is required:
col1<-c("Yes","No", "Yes", NA, NA)
col2<-c("Yes",NA, NA, "No","Yes")
col3<-c("Yes", "Yes", "No", NA ,NA)
Total<-c(3,2,2,1,1)
data<-data.frame(col1,col2,col3,Total, stringsAsFactors = FALSE)
Can anyone suggest a way to achieve this?
Solution 1:[1]
We may use vectorized rowSums on a logical matrix
data$Total <- rowSums(!is.na(data[1:3]))
data$Total
[1] 3 2 2 1 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | akrun |
