Reputation: 1045
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
Reputation: 1956
Use regexp substitution:
sub("^(.).", "\\1x", ba)
Explanation:
Upvotes: 5