-1

I have a dataset where I'd like to use an ifelse() statement that has some sort of startsWith() condition to change another variable.

In plain English it would essentially be "if ID starts with 13 then variable_X == 1"

I understand that grepl has the capability to search through like this but I am unsure how to output a result onto a new or existing variable.

Any ideas on how to begin with this? Thank you!

EDIT: Apologies, as I forgot to mention a crucial detail. There are multiple ID's ranging from 13, 14, 15, 16, etc. I'd like to have my "If ID starts with 13 then variable X == 1" but the else is "do nothing" as to not overlap with over ID numbers. I've also attached a sample dataset showing what I have currently.

ID <- c('13-432', '13-342', '13-546', '14-442', '14-543', 
        '15-332', '15-153', '16-323', '16-654', '16-554')
Outcome <- c(1, 1, 1, 2, 2, 3, 2, 3, 2, 2)
df <- data.frame(ID, Outcome)
       ID Outcome
1  13-432       1
2  13-342       1
3  13-546       1
4  14-442       2
5  14-543       2
6  15-332       3
7  15-153       2
8  16-323       3
9  16-654       2
10 16-554       2

1 Answers1

0

The dplyr way of doing this could be

library(dplyr)

dat <- data.frame(ID = c("131", "140"))

dat |> mutate(variable_X = if_else(startsWith(ID, "13"), 1, 0))

Output

#>    ID variable_X
#> 1 131          1
#> 2 140          0

Created on 2022-04-11 by the reprex package (v2.0.1)

Andrea M
  • 2,314
  • 1
  • 9
  • 27
  • This is good, thanks! One question that I should have included in the original post (and will edit). This will be done multiple times over for different ID's starting with 13, 14, 15, etc.. So I am wondering how to set the `else` condition to keeping the variable as is ,that way I don't overwrite the other ID's with another value. – sixfortyseven Apr 11 '22 at 16:35
  • Please edit the question to add a sample of your dataset and the expected output. See [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) for more info. – Andrea M Apr 11 '22 at 17:27