1

I would like to replace strings with the number of times that a B character is repeated in the string.

This is the representative input df:

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

My expected out output would be like that:

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

Any idea? Thank you!

user2120870
  • 869
  • 4
  • 15

3 Answers3

1

Do you want the vector as characters?

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"

or no

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

# [1] 0 1 2 3 0 2
rawr
  • 19,873
  • 4
  • 42
  • 74
1

You can use regmatches

> match <- regmatches(df, regexpr("B+", df))
> res <- grepl("B+", df)
> res[res]<- nchar(match)
> res
[1] 0 1 2 3 0 2
Jilber Urbina
  • 53,125
  • 10
  • 108
  • 134
1

Here's a gsub nchar approach:

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

nchar(gsub("[^B]", "", df))
## [1] 0 1 2 3 0 2
Tyler Rinker
  • 103,777
  • 62
  • 306
  • 498