Home > Enterprise >  Sum of an elements occurence in R
Sum of an elements occurence in R

Time:10-15

I have a variable called foo that prints out this.

> foo
[1] a
[1] b
[1] a
[1] b
[1] b

It prints out 5 separate results. I want to find the sum of how many b's there are in the variable foo. The answer should be 3. I tried taking the sum, length, etc, but nothing works.

For example, gives me all b's

> sum(foo == 'b')
[1] b
[1] b
[1] b
[1] b
[1] b

Is there a way to combine these separate results into 1 vector, list, or dataframe?

CodePudding user response:

If foo is numeric (as claimed by the PO) this will work as proven by the reprex.

foo <- sample(letters[1:2], 5, replace = TRUE)
foo
#> [1] "b" "a" "a" "a" "b"
base::sum(foo == "b")
#> [1] 2

Created on 2021-10-14 by the reprex package (v2.0.1)

  • Related