How to count with condition how many zeros in a data frame using just one function() in R? -


this question has answer here:

consider following replicable data frame:

col1 <- c(rep("a", times = 5), rep("b", times = 5), rep("c", times = 5)) col2 <- c(0,0,1,1,0,0,1,1,1,0,0,0,0,0,1) data <- as.data.frame(cbind(col1, col2)) 

now data matrix of 15x2. want count how many zeros there condition rows of a's. use table():

table <- table(data$col2[data$col1=="a"]) table[names(table)==0] 

this works fine , result 3.

but real data has 100,000 observations 12 different values of such col1 want make function don't have type above lines of code 12 times.

countzero <- function(row){   table <- table(data$col2[data$col1=="row"])   result <- table[names(table)==0]   return(result) } 

i expected when run countzero(row = a) return 3 instead returns 0, , 0 b , c.

for real data, returns

numeric(0)

which have no idea why.

anyone me out please?

edit: answers showing me how count in total how many zeros each value of col1, works fine, purpose build function returns count of 1 specific col1 value, e.g. a's, because count used later compute other stuff (the percent of 0's in a's, e.g.)

1) aggregate try aggregate:

aggregate(col2 == 0 ~ col1, data, sum) 

giving:

  col1 col2 == 0 1            3 2    b         2 3    c         4 

2) table or try table (omit [,1] if want counts of 1's too):

table(data)[, 1] 

giving:

a b c  3 2 4  

Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -