dasf
dasf

Reputation: 1045

r: lapply value assignment

I want to replace the second letter of every string in the following vector with x.

ba <- c('ba','aba','baba')
# goal: bx, axa, bxba

Normally I would just use substr(ba,2,2) <- 'x'. But for reasons too complicated to go into here, I'm trying to avoid substr and instead looking for another solution. So I tried splitting the strings up and replacing the second element of each list. But I'm getting this error message.

ba2 <- strsplit(ba,'')
lapply(ba2,function(x) x[2]) <- 'x'
# Error in lapply(ba2, function(x) x[2]) <- "x" : 
# could not find function "lapply<-"

How can I work around this problem? Is there a way to use lapply in conjunction with <-?

Upvotes: 2

Views: 157

Answers (1)

Ott Toomet
Ott Toomet

Reputation: 1956

Use regexp substitution:

sub("^(.).", "\\1x", ba)

Explanation:

  • ^ - beginning of word
  • (.) - take an arbitrary character, and memorize it
  • . another arbitrary character
  • \1 - replace by the memorized character
  • ... and 'x'

Upvotes: 5

Related Questions