簡體   English   中英

ifelse 函數中的動態變量名稱

[英]Dynamic variable names within an ifelse-function

我在編寫一個 function 時遇到一些問題,它采用 dataframe 和一個變量名稱為 arguments。然后應該檢查 dataframe 中指定的變量。 如何在 ifelse 語句中使用變量名?

# Some test data

dat <- data.frame(duration = c(198, 1839, 1922, 1928, 99999, 1824),
                  Q1_1 = c(1, 2, 3, 1, 4, 5),
                  Q1_2 = c(2, 2, 3, 1, 5, 3),
                  Q1_3 = c(4, 2, 1, 2, 4, 3),
                  Q1_4 = c(1, 2, 5, 5, 5, 2),
                  Q2_1 = c(0, 0, 1, 0, 1, 1),
                  Q2_2 = c(0, 0, 1, 0, 1, 1),
                  Q2_3 = c(0, 1, 1, 0, 1, 1),
                  Q2_4 = c(1, 0, 1, 0, 1, 1),
                  Q2_5 = c(0, 0, 1, 1, 1, 1),
                  age = c(20, 30, 10, 27, 1, 79),
                  txt1 = c("---", "asfasghjk", ".", "Subway", "Apple pie", "Another answer")
)

# Checker function
check_text <- function(.df, varname){
  #' Function checks for illegal characters in string variable
  
  .df %>% 
  mutate("check_{varname}" := ifelse({{varname}} %in% c(".", "-", "--", "---", "???", "?"), "wrong", "right"))  #<- doesnt work
}

# Apply checker function to test data
dat %>% check_text(varname = "txt1")

當我們傳遞字符串時,轉換為符號並求值 ( !! ) 或使用.data[[varname]] ::rlang::ensym(varname)

check_text <- function(.df, varname){
  #' Function checks for illegal characters in string variable
  .df %>% 
  mutate("check_{varname}" := 
     ifelse(!! rlang::ensym(varname) %in% c(".", "-", "--", "---", "???", "?"), 
       "wrong", "right"))  
}

-輸出

> dat %>% 
  check_text(varname = "txt1")
  duration Q1_1 Q1_2 Q1_3 Q1_4 Q2_1 Q2_2 Q2_3 Q2_4 Q2_5 age           txt1 check_txt1
1      198    1    2    4    1    0    0    0    1    0  20            ---      wrong
2     1839    2    2    2    2    0    0    1    0    0  30      asfasghjk      right
3     1922    3    3    1    5    1    1    1    1    1  10              .      wrong
4     1928    1    1    2    5    0    0    0    0    1  27         Subway      right
5    99999    4    5    4    5    1    1    1    1    1   1      Apple pie      right
6     1824    5    3    3    2    1    1    1    1    1  79 Another answer      right

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM