If string contains x do y in R

Viewed 1082

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!

4 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.

We could use extract_numeric from tidyr package:

library(tidyr)
library(dplyr)
df %>% 
    mutate(test = extract_numeric(ID))

Output:

      ID test
1  Anna1    1
2  Anna1    1
3 Anton2    2
4 Anton2    2

Using case_when

library(dplyr)
library(stringr)
Fixations %>% 
    mutate(test = case_when(str_detect(ID, '1$')~ 1,
       str_detect(ID, '2$') ~ 2))
      ID test
1  Anna1    1
2  Anna1    1
3 Anton2    2
4 Anton2    2

Another option is parse_number

readr::parse_number(Fixations$ID)
[1] 1 1 2 2

data

Fixations <- structure(list(ID = c("Anna1", "Anna1", "Anton2", 
    "Anton2")), class = "data.frame", row.names = c(NA, 
-4L))

How about extracting the string that you want ?

This will extract the number from ID column.

stringr::str_extract(df$ID, '\\d+')
#[1] "1" "1" "2" "2"

If you are interested only in 1 and 2 values and make other numbers as NA you can also specify such pattern in regex.

stringr::str_extract(df$ID, '(1|2)$')
Related