Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If string contains x do y in R

Tags:

string

r

So I'm having a data frame with an ID section that looks something like this

ID
Anna1
Anna1
Anton2
Anton2

I want to create a new variable that contains "1" if there's a 1 in the ID and 2 if there's a "2" in the variable.

So far I've come up with this

Fixations$test <- (ifelse(Fixations$ID %in% 1  ,"1", 
                              ifelse(Fixations$ID  %in% 2, "2", NA)))

Obviously, it doesn't work because my reference to the string is wrong. Can anyone help me with this?

Thanks in advance!

like image 616
Quantizer Avatar asked Nov 19 '25 01:11

Quantizer


1 Answers

You could use grepl:

ifelse(grepl("1", Fixations$ID), "1", 
ifelse(grepl("2", Fixations$ID), "2", NA))

The last parameter defines the value to assign when neither "1" or "2" occurs.

like image 157
Karsten W. Avatar answered Nov 20 '25 17:11

Karsten W.