martinkabe martinkabe - 1 year ago 79
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"),

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 Source

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"

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download