How to assign same id number based on string value R

Viewed 476

I have a vector of strings. each one begins with either f1_ or f2_ .

> lst_c<-c("f1_cat", "f2_cat", "f1_dog", "f1_camel", "f2_camel")
> lst_c
[1] "f1_cat"   "f2_cat"   "f1_dog"   "f1_camel" "f2_camel"

What I want is to just compare everything except the first 3 caracters(f1_/f2_) and assing the same value to them if there is a match

Expected output

> df
      name id_f
1   f1_cat    1
2   f2_cat    1
3   f1_dog    2
4 f1_camel    3
5 f2_camel    3
1 Answers

Here is a way

x <- substring(lst_c, 4, nchar(lst_c))
match(x, unique(x))
# [1] 1 1 2 3 3

nchar(lst_c)

returns the number of characters for each element in lst_c. substring(...) removes the first 3 character from thoses elements in lst_c and returns

x <- substring(lst_c, 4, nchar(lst_c))
x
# [1] "cat"   "cat"   "dog"   "camel" "camel"

Finally we use match to get "the positions of (first) matches of its first argument in its second."

Related