Method for Counting TRUE Values in a Logical Vector

Method for Counting TRUE Values in a Logical Vector, The following techniques can be used to determine how many TRUE values are present in a logical vector in R:

Method 1: Use sum()

Method 2: Use summary()

The examples that follow demonstrate each technique in action.

Highest Paying Data Science Skills-You should know! »

Example1: Count TRUE Values with sum ()

The number of TRUE values in a logical vector can be counted using sum() as seen in the code below:

We can now construct a logical vector.

x <- c(TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, NA, NA)

Count the TRUE values in the vector.

sum(x, na.rm=TRUE)
[1] 2

We can see from the result that the vector has 2 TRUE values.

The function will return NA if the vector contains NA values and the na.rm=TRUE argument is not used.

Not Satisfied with statistical significance (p-value) »

Example 2: Count TRUE Values Using summary()

How to use summary() to count the number of TRUE, FALSE, and NA values in a logical vector is demonstrated in the code below:

We can now develop a logical vector.

x <- c(NA, FALSE, FALSE, TRUE, FALSE, FALSE, NA, TRUE)

Now we can create a count of TRUE, FALSE, and NA values in the vector

summary(x)
Mode   FALSE    TRUE    NA's
logical       4       2       2

The output reveals the following:

The vector contains 4 FALSE values.

The vector has two TRUE values.

The vector has two NA values.

If you want to know how often each sort of value appears in a logical vector, the summary() function is quite helpful.

The following syntax can be used to just return the number of TRUE values from the summary() function:

Let’s count TRUE values in the vector

summary(x)['TRUE']
TRUE
   2

Introduction to Hadoop Data Processing Applications »

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

eighteen − 4 =