Sunday, 15 January 2012

r - Assign values to a variable, conditional on a factor variable -



r - Assign values to a variable, conditional on a factor variable -

i want create variable takes values numeric vector, conditional on factor variable.

i have factor variable z taking values a, b, c,..., k.

i have numeric vector

x <- c(0, 1000, 50000)

my info frame like:

id z 1 1 2 2 3 3 c 4 4 na 5 5 b 6 6 7 7 na 8 8 na

i want create variable y:

y=x[1] if z==a, y=x[2] if z==b, y=x[3] if z==c

and, like:

id z y 1 1 0 2 2 0 3 3 c 50000 4 4 na na 5 5 b 1000 6 6 0 7 7 na na 8 8 na na

i tried using like

df$y[which(df$z == "a")] <- x[1] df$y[which(df$z == "b")] <- x[2] df$y[which(df$z == "c")] <- x[3]

but achieves nil (it gives variable y total of na's).

this describe , insert na y column if z not a, b, or c.

set.seed(84) df <- data.frame(z = sample(letters[1:11], 15, replace = true)) x <- c(0,1000,50000) df$y <- ifelse(df$z == "a", x[1], ifelse(df$z == "b", x[2], ifelse(df$z == "c", x[3], na))) df # z y # 1 na # 2 d na # 3 j na # 4 na # 5 c 50000 # 6 c 50000 # 7 b 1000 # 8 d na # 9 g na # 10 b 1000 # 11 na # 12 k na # 13 j na # 14 k na # 15 0

it's unclear post should happen if z not a, b, c; if real needs more complicated, nested ifelse() statements pretty cumbersome.

r conditional vectorization

No comments:

Post a Comment