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


i'm having little bit of problem attempting set multitude of variables specific value (-99) based on value of variable. comes in 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 example dataframe instance. usually, accomplish setting v2 thorugh v5 -99, if v1 "blue", end doing several statements ...

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

obviously approach has multitude of drawbacks, since of data sets can large. in program, use statement ...

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

i've been attempting use for-loop in r without avail few attempts revolve around statements, such this..

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

if give me hand i'm attempting here, appreciate it. i'm thinking may overthinking it, , able apply family of functions.

output, should 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!

we can use logical index x$v1 == "blue" subset rows , -1 remove first column non-numeric column, , assign -99.

x[x$v1 == "blue", -1] <- -99 x #    v1  v2  v3  v4  v5 #1 blue -99 -99 -99 -99 #2 blue -99 -99 -99 -99 #3  red   3   3   1   3 #4  red   4   4   2   4 #5 blue -99 -99 -99 -99 

an efficient approach set data.table. convert 'data.frame' 'data.table' (setdt(x)), loop through columns 2 last column, , set 'value' each column based on logical index in 'i'.

library(data.table) setdt(x) for(j in 2:ncol(x)){    set(x, = which(x$v1 =="blue"), j = j, value = -99) } 

Comments