I would like to make my code more efficient, I have a survey where my data looks like:
survey <- data.frame(
x = c(1, 6, 2, 60, 75, 40, 27, 10),
y = c(100, 340, 670, 700, 450, 200, 136, 145))
#Two lists:
A <- c(3, 6, 7, 27, 40, 41)
t <- c(0.10, 0.11, 0.12, 0.13, 0.14, 0.15, 0.16)
What I did was create new columns, like this:
z <- ifelse(survey$x %in% A), 0, min(t))
for (i in t) {
survey[paste0("T",i)] <-z
survey[paste0("T",i)] <-ifelse (z > 0, i, z)
}
But with that code it takes a while, is there a better way to do it?
survey[paste0("T", t)] <- lapply(t, function(y) ifelse(survey$x %in% A, 0, y))
– Polypusdata.table
which might be faster i.e.setDT(survey)[, paste0("T", t) := 0]; for(j in t) { set(survey, i = which(!survey$x %in% A), j = paste0("T", j), value = j)
} – Polypus