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
  • 16

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
  • 20,481
  • 4
  • 44
  • 78
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
  • 58,147
  • 10
  • 114
  • 138
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
  • 108,132
  • 65
  • 322
  • 519