سؤال

I have a string of characters.

c = c("a", "about", "base", "base", "h2o", "h", "yes", "a", "c", "h", "d")

I need to find out how many times a specific single letter, e.g. "a", "c", "h", "d", are repeated in the strings. I have tried

grep("a", c, fixed=TRUE, useBytes=TRUE)

But it will gives all the positions where "a" appears, including "about" and "base". I have also tried

match("a", c)

Sadly, it only gives the position of the 1st match and ignores the following matches.

How can get all the position of "a", which should be 1 and 8?

هل كانت مفيدة؟

المحلول

It sounds like you're just looking for table and which:

String <- c("a", "about", "base", "base", "h2o", "h", "yes", "a", "c", "h", "d")
table(String)
# String
#     a about  base     c     d     h   h2o   yes 
#     2     1     2     1     1     2     1     1 

which(String == "a")
# [1] 1 8

nchar(String)
#  [1] 1 5 4 4 3 1 3 1 1 1 1

table(String[nchar(String) == 1])
# 
# a c d h 
# 2 1 1 2 

نصائح أخرى

You could just alter you regular expression within grep

v = c("a", "about", "base", "base", "h2o", "h", "yes", "a", "c", "h", "d")
grep("^a$", v)
#[1] 1 8
length(grep("^a$", v))
#[1] 2
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top