0

if I have a vector

x <- c("aa/bb","cc/aa","aa/dd", "bb/cc")

I want to get a output for specif substrings such as for "aa" and "bb":

aa = 3
bb = 2

This frequency can be calculated of irrespective of the position. Kindly let me know do we have a function for this or we need to write a separate function.

Thanks in advance.

d.b
  • 32,245
  • 6
  • 36
  • 77
R_to_kn
  • 23
  • 4

1 Answers1

1

You could split x at / and use table to count the frequency.

table(unlist(strsplit(x, "/")))

#aa bb cc dd 
# 3  2  2  1 

If you want to count specific substrings, you could do

library(stringr)
sapply(c("aa", "bb"), function(ss) sum(str_count(x, ss)))
#aa bb 
# 3  2 
d.b
  • 32,245
  • 6
  • 36
  • 77