jeudi 21 juillet 2016

R - Assigning multiple values based on one vector (if x = 1, set these variables = -99)

I'm having a little bit of a problem with attempting to set a multitude of variables to a specific value (-99) based on the value of another variable. This frequently comes up in my survey work.

v1 <- c("Blue","Blue","Red","Red","Blue")
v2 <- c(1,2,3,4,5)
v3 <- c(1,2,3,4,5)
v4 <- c(1,1,1,2,2)
v5 <- c(1,2,3,4,5)

x = data.frame (v1,v2,v3,v4,v5)

Take this example dataframe for instance. Usually, to accomplish setting v2 thorugh v5 to -99, if v1 was "Blue", I would end up doing several statements like this ...

x$v2[x$v1 == "Blue"] <- -99
x$v3[x$v1 == "Blue"] <- -99

Obviously this approach has a multitude of drawbacks, especially since some of my data sets can be large. In another program, I would use a statement like this ...

(for i in v2:v5, 
if v1 = Blue, set i = -99)

I've been attempting to use a for-loop in R without too much avail a few my attempts revolve around statements, such as this..

for(i in x$v2:v5){
i[x$v1 == "Blue"] <- -99 
}

If anyone could give me a hand with what i'm attempting to do here, I would greatly appreciate it. I'm thinking that I may be overthinking it, and able to do something like this with the apply family of functions.

Output, should look like this..

v1 <- c("Blue","Blue","Red","Red","Blue")
v2 <- c(-99,-99,3,4,-99)
v3 <- c(-99,-99,3,4,-99)
v4 <- c(-99,-99,1,2,-99)
v5 <- c(-99,-99,3,4,-99)
x = data.frame (v1,v2,v3,v4,v5)

Thanks Again Everyone!

Aucun commentaire:

Enregistrer un commentaire