I have a question how to write a loop in r which goes checks if a certain expression occurs in a string . So I want to check if the the expression “i-sty” occurs in my variable for each i between 1:200 and, if this is true, it should give the corresponding i.
For example if we have “4-sty” the loop should give me 4 and if there is no “i-sty” in the variable it should give me . for the observation.
I used
for (i in 1:200){
datafram$height <- ifelse(grepl("i-sty", dataframe$Description), i, ".")
}
But it did not work. I literally only receive points. Attached I show a picture of the string variable. enter image description here
iin it. To you use a regex pattern with your variablei, you need to paste together a string, e.g.,grepl(paste0(i, "-sty"), ...). I'd also recommend usingNArather than"." for the "else" result - that way the resultingheightvariable can be numeric.x <- c("6-sty xxx", "4-sty yyyy", NA, "sty zzz", "32-sty xyz"); as.numeric(sub("^([0-9]+)-sty.*", "\\1", x))