switch statement - How can I assign a value based on 2 conditions in R? -
first data, question:
df <- data.frame(z=c(1,2,3),y=c(2,3),a=c(1,2,3,4,5,6)) df z y 1 2 1 2 2 2 3 2 3 1 3 4 2 3 5 3 3 6
i using r , generate vector given vector z
, y
. if (z1==1 & y1==2)
, a1=1
, if (z3==3 & y1==2)
, a1=3
....if have 1 condition (z
or y
), generate a
switch function, however, how generate a
z
, y
?
if understood question correctly answer follows. if misunderstood please correct me.
df <- data.frame(z=c(1,2,3),y=c(2,3),a=c(1,2,3,4,5,6)) df$a <- na # empty out # re-create df$a[df$z == 1 & df$y == 2] <- 1 df$a[df$z == 2 & df$y == 2] <- 2 df$a[df$z == 3 & df$y == 2] <- 3 df$a[df$z == 1 & df$y == 3] <- 4 df$a[df$z == 2 & df$y == 3] <- 5 df$a[df$z == 3 & df$y == 3] <- 6 df <- df[order(df$a),] df
z y 1 1 2 1 5 2 2 2 3 3 2 3 4 1 3 4 2 2 3 5 6 3 3 6
Comments
Post a Comment