2017-10-18 133 views
0

我讀過Programming with dplyr文檔,並試圖編寫一個圍繞case_when()函數的簡單函數。在dplyr :: case_when中使用NSE

library(dplyr) 
data_test <- data.frame(
    a = rep(c("a", "b", "c"), each = 5), 
    b = rnorm(15) 
) 

fun_test <- function(df, var1, var2) { 

    var1 <- enquo(var1) 
    var2 <- enquo(var2) 

    df <- mutate(df, 
       c = case_when(
        !!var1 == "a" ~ 1, 
        !!var1 == "b" ~ 2, 
        !!var1 == "c" ~ 3 
       ), 
       d = case_when(
        !!var2 > 0 ~ 1, 
        !!var2 < 0 ~ 0 
       )) 

    df 

} 

fun_test(data_test, a, b) 

我希望新列cd將基於在ab值來創建的,而是他們只是NA0。任何想法,爲什麼是這種情況?

乾杯。

回答

2

您需要大約括號!瓦爾,所以!!var1 == "a" ~ 1應該(!!var1) == "a" ~ 1


fun_test <- function(df, var1, var2) { 

    var1 <- enquo(var1) 
    var2 <- enquo(var2) 

    df <- mutate(df, 
       c = case_when(
        (!!var1) == "a" ~ 1, 
        (!!var1) == "b" ~ 2, 
        (!!var1) == "c" ~ 3 
       ), 
       d = case_when(
        (!!var2) > 0 ~ 1, 
        (!!var2) < 0 ~ 0 
       )) 

    df  
} 

fun_test(data_test, a, b) 

# a   b c d 
# 1 a 0.70352390 1 1 
# 2 a -0.10567133 1 0 
# 3 a -1.25864863 1 0 
# 4 a 1.68443571 1 1 
# 5 a 0.91139129 1 1 
# 6 b 0.23743027 2 1 
# 7 b 1.21810861 2 1 
# 8 b -1.33877429 2 0 
# 9 b 0.66082030 2 1 
# 10 b -0.52291238 2 0 
# 11 c 0.68374552 3 1 
# 12 c -0.06082195 3 0 
# 13 c 0.63296071 3 1 
# 14 c 1.33551762 3 1 
# 15 c 0.00729009 3 1