I want to replace the first element of the strings in x with blank if it satisfies the condition : If first element of "101" in x matches the first string in y, replace first element of "101" with blank.
x = c("101", "201", "301")
y = c("1", "7", "3")
Want:
> x
[1] "01" "201" "01"
I was trying:
> ifelse(substr(x, 1, 1) == y, sub(substr(x, 1, 1), ""), x)
I know this is wrong though not intuitively- sub
needs a pattern as first argument and won't take substr
.
Also tried :
> ifelse(substr(x, 1, 1) == y, substr(x, 1, 1) <- "", x)
[1] "" "201" ""
I referred this R: How can I replace let's say the 5th element within a string? and solved it using :
ifelse(substr(x, 1, 1) == y, paste(substr(x, 2, nchar(x))), x)
wondering if there is a better way of doing this ?
The regex to match the first character is "^."
(^
is start of string, .
is any single character), so use sub
just like you suggest:
ifelse(substr(x, 1, 1) == y, sub("^.", "", x), x)
# [1] "01" "201" "01"
Don't know if it's better, but you could always use mapply()
in a situation like this:
x <- c("apple", "bog", "cat", "dog")
y <- c('a', 'b', 'b', 'd')
logi <- mapply(`==`, substr(x,1,1), y)
substr(x[logi],1,1) <- ""
x
[1] "pple" "og" "cat" "og"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With