Frage

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?

War es hilfreich?

Lösung

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 

Andere Tipps

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top