I am a recent convert to R and am struggling to find the R equivalent of the following: looping over variables named with a common prefix plus a number (var1, var2, ..., varn).
Say I have a dataset where each row is a store and each column is the value of that store's revenue in month 1, month 2...month 6. Some made-up data for example:
store = c("a", "b", "c", "d", "c")
rev1 = c(500, 200, 600, 400, 1200)
rev2 = c(260, 100, 450, 45, 1300)
rev3 = c(500, 150, 610, 350, 900)
rev4 = c(480, 200, 600, 750, 1000)
rev5 = c(500, 68, 750, 350, 1200)
rev6 = c(510, 80, 1000, 400, 1450)
df = data.frame(store, rev1, rev2, rev3, rev4, rev5, rev6)
I am trying to do something like the following:
varlist <- paste("rev", 1:6) #create list of variables rev1-rev6 #
for i in varlist {
highrev[i] <- ifelse(rev[i] > 500, 1, 0)
}
So for each existing variable rev1:rev6, create a variable highrev1:highrev6 which equals 1 if rev1:rev6 > 500 and 0 otherwise.
Can you suggest an appropriate means of doing this?