문제

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