在dplyr case_when()中使用动态变量名
我在R中有一个函数,在下列情况下使用case_:在dplyr case_when()中使用动态变量名,r,dplyr,R,Dplyr,我在R中有一个函数,在下列情况下使用case_: myfunction <- function(df, col, case_name, cntl_name) { object <- df %>% mutate( class = case_when( col == case_name ~ 1, col == cntl_name ~ 0, ) ) return(object) }
myfunction <- function(df, col, case_name, cntl_name) {
object <- df %>%
mutate(
class = case_when(
col == case_name ~ 1,
col == cntl_name ~ 0,
)
)
return(object)
}
但它没有-它返回这个:
> newdf
id phenotype treatment weeks_of_treatment class
1 ID1 blue treat1 0 NA
2 ID2 blue treat2 0 NA
3 ID3 red none 0 NA
4 ID4 green none 0 NA
5 ID5 red none 0 NA
它不会将变量col
识别为列表型
。当时,有人知道如何将动态变量输入到案例中吗
我曾尝试过dplyr中变量的其他解决方案(例如,在col
[[col]]
)周围使用双括号,但我找不到有效的解决方案。myfunction我认为您更接近于使用[[col]]]
的解决方案:{col}
。我怀疑,问题在于tidyverse使用了非标准评估,或者。
myfunction <- function(df, col, case_name, cntl_name) {
object <- df %>%
mutate(
class = case_when(
{{col}} == case_name ~ 1,
{{col}} == cntl_name ~ 0,
)
)
return(object)
}
myfunction(df, phenotype, "red", "blue")
id phenotype treatment weeks_of_treatment class
1 ID1 blue treat1 0 0
2 ID2 blue treat2 0 0
3 ID3 red none 0 1
4 ID4 green none 0 NA
5 ID5 red none 0 1
id phenotype treatment weeks_of_treatment class
1 ID1 blue treat1 0 0
2 ID2 blue treat2 0 0
3 ID3 red none 0 1
4 ID4 green none 0 NA
5 ID5 red none 0 1
> newdf
id phenotype treatment weeks_of_treatment class
1 ID1 blue treat1 0 NA
2 ID2 blue treat2 0 NA
3 ID3 red none 0 NA
4 ID4 green none 0 NA
5 ID5 red none 0 NA
myfunction <- function(df, col, case_name, cntl_name) {
object <- df %>%
mutate(
class = case_when(
{{col}} == case_name ~ 1,
{{col}} == cntl_name ~ 0,
)
)
return(object)
}
myfunction(df, phenotype, "red", "blue")
id phenotype treatment weeks_of_treatment class
1 ID1 blue treat1 0 0
2 ID2 blue treat2 0 0
3 ID3 red none 0 1
4 ID4 green none 0 NA
5 ID5 red none 0 1
myfunction <- function(df, col, case_name, cntl_name) {
qCol <- enquo(col)
object <- df %>%
mutate(
class = case_when(
!! qCol == case_name ~ 1,
!! qCol == cntl_name ~ 0,
)
)
return(object)
}