How can we count TRUE values in a logical vector?

0 votes
Apr 19, 2018 in Data Analytics by shams
• 3,580 points
802 views

1 answer to this question.

0 votes
In the cases of problems where logical vector contains NA values.

a <- c(TRUE, FALSE, NA)
sum(a) # gives you NA
table(a)["TRUE"] # gives you 1
length(a[a==TRUE]) # f3lix answer, gives you 2 (because NA indexing returns values)

sum(a, na.rm=TRUE) # best way to count TRUE values #which gives 1.

You should be careful with the "table" solution, in case there are no TRUE values in the logical vector.
Suppose a <- c(NA, FALSE, NA) or simply a <- c(FALSE, FALSE)

table(a)["TRUE"] # gives you NA for both cases.
answered Apr 19, 2018 by zombie
• 3,690 points

Related Questions In Data Analytics

0 votes
1 answer

How to count the number of elements with the values in a vector?

You have various options to count the ...READ MORE

answered Apr 12, 2018 in Data Analytics by darklord
• 6,140 points
69 views
0 votes
1 answer

How can I delete multiple values from a vector in R?

The %in% operator tells  which elements are ...READ MORE

answered Apr 26, 2018 in Data Analytics by shams
• 3,580 points
71 views
0 votes
3 answers

How to remove NA values from a Vector in R?

using the function "complete.cases" for example, if you ...READ MORE

answered Jun 18 in Data Analytics by anonymous
4,692 views
0 votes
1 answer

How to write a custom function which will replace all the missing values in a vector with the mean of values in R?

Consider this vector: a<-c(1,2,3,NA,4,5,NA,NA) Write the function to impute ...READ MORE

answered Jul 4, 2018 in Data Analytics by CodingByHeart77
• 3,680 points
96 views
0 votes
1 answer
0 votes
1 answer

How can you find total number of null values in a dataset column wise?

You can write a custom sapply function ...READ MORE

answered Oct 12, 2018 in Data Analytics by ANMOL
• 3,620 points
25 views
+1 vote
1 answer

Custom Function to replace missing values in a vector with the mean of values

You have missed out on "na.rm=TRUE" inside ...READ MORE

answered Mar 27, 2018 in Data Analytics by Bharani
• 4,550 points
48 views
0 votes
1 answer

How to count unique values in R?

You can get the information printed in ...READ MORE

answered Apr 9, 2018 in Data Analytics by darklord
• 6,140 points
944 views
0 votes
1 answer

How can I drop columns by name in a data frame ?

We can Drop Columns by name in ...READ MORE

answered Apr 13, 2018 in Data Analytics by zombie
• 3,690 points
29 views
0 votes
1 answer

How can we trim leading and trailing whitespaces in R?

trimws {base} //Remove Leading/Trailing Whitespace Removes leading and/or ...READ MORE

answered Apr 18, 2018 in Data Analytics by zombie
• 3,690 points
358 views