I'm looking to create a total column that counts the number of cells in a particular row that contains a character value. The values will only be 1 of 3 different letters (R or B or D). So using the example from the script below, outcomes will be: p1=
2, p2=1
, p3=2
, p4=1
, p5=1
I'm thinking using nrow
with a condition would be the way to go, but I'm unable to get that to work. Something like this:
# count the number of columns where the cell is not blank (or contains an R,B,D)
test$tot <- nrow(!test="")
Any help is much appreciated!
---------------- script for reference:
column1 <- c("p1","p2","p3","p4","p5")
column2 <- c("R","","R","R","")
column3 <- c("","B","","","B")
column4 <- c("D","","D","","")
test <- data.frame(column1,column2,column3,column4)
colnames(test)[c(1:4)] <- c("pol_nbr","r1","r2","r3")
View(test)
Using rowSums
:
test$tot_cols <- rowSums(test[, -1] != "")