Say my data(imaginary) ,a data frame is as follows :
> head(data)
mpg_H cyl_G disp_G
Mazda RX4 TRUE TRUE TRUE
You can use apply
and sum
.
df$count_TRUE <- apply(df, 1,sum);
df$count_FALSE <- (ncol(df)-1)-df$count_TRUE;
Try rowSums
or Reduce
count_TRUE <- rowSums(df) # Or count_TRUE <- Reduce(`+`, df)
df[c("count_TRUE", "count_FALSE")] <- cbind(count_TRUE, ncol(df) - count_TRUE)
df
# mpg_H cyl_G disp_G count_TRUE count_FALSE
# Mazda RX4 TRUE TRUE TRUE 3 0
# Mazda RX4 Wag TRUE FALSE FALSE 1 2
# Datsun 710 FALSE FALSE FALSE 0 3
# Hornet 4 Drive FALSE TRUE TRUE 2 1
# Hornet Sportabout TRUE TRUE TRUE 3 0
# Valiant TRUE TRUE FALSE 2 1