Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace first element of a string in R based on a condition

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 ?

like image 654
vagabond Avatar asked Jan 09 '23 19:01

vagabond


2 Answers

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" 
like image 147
Gregor Thomas Avatar answered Feb 11 '23 21:02

Gregor Thomas


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"  
like image 42
Richard Border Avatar answered Feb 11 '23 20:02

Richard Border