lundi 27 novembre 2017

Loop to add new columns with ifelse in R

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?

Aucun commentaire:

Enregistrer un commentaire