1

我正在尝试在 adplyr pipelapply函数中使用动态字符串。其中字符串用于命名列,该列稍后在filter. 尝试过滤以!is.na()删除filter.

通常,对于这种情况,人们会使用非标准评估filter_,但是由于被调用的字符串在 内is.na()filter_因此没有效果。我要求使用主符号 (`) 而不是引号 (") 来调用字符串。

下面是一个减去lapply函数的最小示例。

df <- data.frame("one"=c(1,2,3,4),"two"=c(4,NA,2,1))
storeddate <- "Jan17-01-92"
finaldf <- df %>%
 mutate(!!storeddate := one+two) %>%
 filter(!is.na(storeddate)) #the storeddate string call requires formatting as `Jan17-01-92` as opposed to "Jan17-01-92".

我知道我可以简单地重新格式化初始字符串,但是我更好奇找到一种方法来调用以不同格式包装的字符串以在其他场景中使用。

4

2 回答 2

1

在调用中添加!!取消引用运算符is.na

finaldf <- df %>%
 mutate(!!storeddate := one+two) %>%
 filter(!is.na(!!storeddate))
于 2018-04-19T19:17:04.007 回答
1

对于过滤器,您需要将字符串转换为符号。例如

df %>%
  mutate(!!storeddate := one+two) %>% 
  filter(!is.na(!!as.name(storeddate)))

#   one two Jan17-01-92
# 1   1   4           5
# 2   3   2           5
# 3   4   1           5

所以这不是替换引号。它在 R 中的字符串和符号/名称之间有所不同。

于 2018-04-19T19:30:41.253 回答