How to create a new variable with values from diff

2019-06-10 14:15发布

问题:

I have a complicated question that I will try to simplify by simplifying my dataset. Say I have 5 variables:

df$Id <- c(1:12)
df$Date <- c(NA,NA,a,a,b,NA,NA,b,c,c,b,a)
df$va <- c(1.1, 1.4, 2.5, ...)     #12 randoms values
df$vb <- c(5.9, 2.3, 4.7, ...)     #12 other random values
df$vc <- c(3.0, 3.3, 3.7, ...)     #12 more random values

Then I want to create a new variable that takes the value from va, vb, or vc if the date is equal to a, b, or c. I had tried a nested if-else, which did not work. I also tried:

df$new[df$date=='a' & !is.na(df$date)] <- df$va
df$new[df$date=='b' & !is.na(df$date)] <- df$vb
df$new[df$date=='c' & !is.na(df$date)] <- df$vc

This correctly left NA's in the new variable where Date=NA, however the values provided were not from va, vb, or vc, but some other value altogether. How can I get df$new to equal va if the date is 'a', vb if the date is 'b', and vc if the date is 'c'?

回答1:

You want the ifelse function, which is a vectorized conditional:

 > x <- c(1, 1, 0, 0, 1)
 > y <- c(1, 2, 3, 4, 5)
 > z <- c(6, 7, 8, 9, 10)
 > ifelse(x == 1, y, z)
 [1] 1 2 8 9 5

You will have to nest calls to this function, like this:

> x_1 <- c(1, 1, 0, 0, 1)
> x_2 <- c(1, 1, 1, 0, 1)
> y_1 <- c(1, 2, 3, 4, 5)
> y_2 <- c(6, 7, 8, 9, 10)
> z <- c(0, 0, 0, 0, 0)
> ifelse(x_1 == 1, y_1,
+   ifelse(x_2 == 1, y_2, z)
+ )
[1] 1 2 8 0 5

Your second attempt would succeed if you made the following modification:

df$new[df$date=='a' & !is.na(df$date)] <- df$va[df$date=='a' & !is.na(df$date)]

To avoid the new variable becoming a list rather than a numeric variable, use %in% in place of ==:

df$new[df$date %in% 'a' & !is.na(df$date)] <- df$va[df$date  %in% 'a' & !is.na(df$date)]


标签: r subset