martinkabe martinkabe - 1 month ago 9
R Question

Filtering with logical + NA values in one column in r

I have the following data frame:

df <- data.frame("Logical"=c("true",NA,"false","true","","false"),
"Numeric"=c(1,2,3,4,5,6))

unique(df$Logical)
length(df$Logical == TRUE)


I'm trying to figure out, how many TRUE values do I have in my df$Logical column. But seems I'm missing something and length(df$Logical == TRUE) returns no of records in my logical column.

What I'm doing wrong in this particular case. Desired result should be 2 for TRUE values in df$Logical column. Many thanks in advance.

Answer

We need to specify the string in the lower case as the values were 'true/false' and not exactly TRUE/FALSE. Also, instead of length, sum should be used. The sum gets the number of TRUE elements.

sum(df$Logical == "true")
#[1] 2

If there are NA elements in the column, use na.rm = TRUE

sum(df$Logical=='true', na.rm = TRUE)
#[1] 2

The length of a logical or any other vector would be the same as the original length/number of rows of the dataset.

length(df$Logical == "true")
#[1] 6

because it returns a logical vector of length 6.

df$Logical == "true"
#[1]  TRUE FALSE FALSE  TRUE FALSE FALSE

To get the counts of both true and false, we can use table

table(df$Logical)
Comments