Count number of columns with TRUE in data frame

1.4k Views Asked by At

I am trying to count the number of columns that contain the word "TRUE" in every row of a data frame and then place that number in a new column of that data frame. For example, how do I go from this

A     B       C       D       E       F       H       I
###   TRUE    FALSE   TRUE    TRUE    +       ###     Text
###   TRUE    TRUE    TRUE    TRUE    +       ###     Text
###   FALSE   FALSE   FALSE   FALSE   +       ###     Text

To this

A     B       C       D       E       F       H       I       J
###   TRUE    FALSE   TRUE    TRUE    +       ###     Text    3
###   TRUE    TRUE    TRUE    TRUE    +       ###     Text    4
###   FALSE   FALSE   FALSE   FALSE   +       ###     Text    0

Where column J now contains the number of TRUE in the row.

I used '###' and '+' and 'Text' to denote that my data frame does not just contain numeric values. Ideally I would like to just count the number of times TRUE appears in a select group of columns, something like this

df[,c(2:5)]

rather than counting the number of TRUE across the entire row (in case one of the text values happened to be 'TRUE').

1

There are 1 best solutions below

0
akrun On

We may use rowSums as TRUE -> 1 and FALSE -> 0, thus each TRUE element when summed gives the count

df$J <- rowSums(df[2:5], na.rm = TRUE)