r语言 - 有一种方法来提供参数到一个dplyr函数使用字符串变量?这叫什么?



在R中是否有一种方法可以像这样为函数提供参数(?):

df <- data.frame( ID = c(10, 20),
strand = c(1,-1),
type = c("pos", "neg") )
test1 <- "strand == "-1""
test2 <- "type == "pos""
df %>% dplyr::filter(test1)
df %>% dplyr::filter(test2)

我的最终目标是一个函数,它将根据用户偏好使用一列或另一列过滤df:

strand_or_type <- function(df, strand_or_type) { 
df <- data.frame( ID = c(10, 20),
strand = (1,-1),
type = ("pos", "neg") )
if(strand_or_type == "strand"){
col <- "strand == "-1""
} else if(strand_or_type == "type") {
col <- "type == "pos""
}
df %>% dplyr::filter(col)
}

也许有更好的方式来描述这个,如果有,我会尽快更新。对不起。

我们可以用parse_expr

library(dplyr)
df %>%
dplyr::filter(eval(rlang::parse_expr(test1)))

作为函数

strand_or_type <- function(df, strand_or_type) { 
str1 <- switch(strand_or_type,
strand = "strand == "-1"",
type = "type == "pos"")
df %>%
filter(eval(rlang::parse_expr(str1)))
}

测试

strand_or_type(df, "strand")
ID strand type
1 20     -1  neg
> strand_or_type(df, "type")
ID strand type
1 10      1  pos

或者不创建字符串并求值,而可以使用

strand_or_type <- function(df, strand_or_type) { 
to_filter <- switch(strand_or_type,
strand = -1,
type = "pos")
df %>%
filter(if_any(all_of(strand_or_type), ~ .x == to_filter))
}

测试

> strand_or_type(df, "strand")
ID strand type
1 20     -1  neg
> strand_or_type(df, "type")
ID strand type
1 10      1  pos

使用filter_,您可以传递字符串。

strand_or_type <- function(df, strand_or_type) { 
if(strand_or_type == "strand"){
col <- "strand == "-1""
} else if(strand_or_type == "type") {
col <- "type == "pos""
}

dplyr::filter_(df,col)
}

最新更新