R - check for substring within string, if true then add value to a different variable

4.2k views Asked by At

I want to do something that I am sure is very simple, but I have little R experience.

I have a variable with value that are different strings. I want to check if each value contains a substring, and, if so, to add another value to a DIFFERENT variable.

I'm trying something like this:

if (grep(ws$stim,'80m')==TRUE)  {
  ws$distance <- 80
  return(ws)
} else {
  return(ws)
}

IE. "If any value in the variable 'stim' contains the substring '80m', then change the value for the variable 'distance' to '80'."

I hope that is clear. Can anyone help me out with this?

1

There are 1 answers

0
akrun On BEST ANSWER

You can try

 ws$distance[grep('80m', ws$stim)] <- 80

data

set.seed(24)
ws <- data.frame(distance=sample(40:90, 20, replace=TRUE), 
       stim=sample(paste0(c(20,40,60,80),'m'), 20,
         replace=TRUE), stringsAsFactors=FALSE)