0
df <- data.frame(
    cola = c('1','b','c','1','1','e','1',NA,'c','d'),
    colb = c("A",NA,"C","D",'a','b','c','d','c','d'),
    colc = c('a','b','c','d','a','b','c','d','c','d'),stringsAsFactors = TRUE)

df$cola is 1 b c 1 1 e 1 <NA> c d
I want to know how many 1 in this column(answer is 4),how to do it?

kittygirl
  • 2,255
  • 5
  • 24
  • 52

1 Answers1

2

You may use sum here:

num_ones <- sum(df$cola == "1", na.rm=TRUE)
num_ones

[1] 4

The na.rm=TRUE option is needed, because without it, the entire sum operation would "NA out", and just return NA. In this case, we can just ignore NA values.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360