将字符串替换为 R 中特定字符的等效数量

Replace strings to equivalent number of a specific character in R

我想用 B 字符在字符串中重复的次数替换字符串。

这是代表输入df:

df <- c("AA", "AB", "BB", "BBB", "D", "ABB")

我预期的 out 输出是这样的:

out <- c("0", "1", "2", "3", "0", "2")

有什么想法吗?谢谢!

你想要向量作为字符吗?

df <- c("AA", "AB", "BB", "BBB", "D", "ABB")
sapply(strsplit(df, ''), function(x) as.character(sum(x == 'B')))

# [1] "0" "1" "2" "3" "0" "2"

或者没有

df <- c("AA", "AB", "BB", "BBB", "D", "ABB")
sapply(strsplit(df, ''), function(x) sum(x == 'B'))

# [1] 0 1 2 3 0 2

您可以使用regmatches

> match <- regmatches(df, regexpr("B+", df))
> res <- grepl("B+", df)
> res[res]<- nchar(match)
> res
[1] 0 1 2 3 0 2

这是一个 gsub nchar 方法:

df <- c("AA", "AB", "BB", "BBB", "D", "ABB")

nchar(gsub("[^B]", "", df))
## [1] 0 1 2 3 0 2