I want to create a new variable "x" by comparing the values of a variable to those of several variables, for example, from the sample excel dataset, I want to do the following:
if (b<=perc1) { x=day1}
else if (b>perc[dim(k)-1]) {x=day[dim(k)] } # k=5 from the attached data as we have perc1 to perc5.
else for (b=2: dim(k)-1){
if (perc[b-1]<b<=perc[b] ) {x=day[b]}
}
Sorry guys, I made a mistake in my original codes; Please see updated code below
if (b<=perc1) { x=day1}
else if (b>perc[dim(k)-1]) {x=day[dim(k)] } # k=5 from the attached data as we have perc1 to perc5.
else for (j=2: dim(k)-1){
if (perc[j-1]<b<=perc[j] ) {x=day[j]}
}
This works perfect, thank you. However, what if I have several variables, e.g. perc1, perc2, ..., perc21 and day1, day2, ..., day21, is there a way to generalize the codes?
I can't find a way to automatically construct the conditions of the case_when(). It is easy enough to build a vector of strings that look like the correct formulas or to build a single string containing all of the formulas, but I can't find a way to convert them to formula objects that case_when() will take.
A for loop can be used to write a more flexible method .
DF <- read.csv("~/R/Play/Dummy.csv", sep = " ")
DF$x <- NA
for (i in 2:5) {
DF$x <- ifelse(DF$b > DF[[paste0("perc", i-1)]], DF[[paste0("day", i)]], DF$x)
}
DF$x <- ifelse(DF$b <= DF$perc1, DF$day1, DF$x)