【问题标题】:Error in UseMethod("escape") : no applicable method for 'escape' applied to an object of classUseMethod(“escape”)中的错误:没有适用于“escape”的方法应用于类对象
【发布时间】:2019-09-12 08:11:15
【问题描述】:

当我在远程 Postgres 数据库上尝试一些代码时,我收到以下错误消息。

以下 peusdo 复制代码在数据帧是本地的时运行良好,但在远程时则不行。

library(tidyverse)
library(dbplyr)
library(RPostgres)


event <- tibble(id = c("00_1", "00_2", "00_3", "00_4", "00_5", "00_6", "00_7"),
               type_id = c("A", "B", "C", "B", "A", "B", "C"))


detail <- tibble(id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L),
                event_id = c("00_1", "00_1", "00_2", "00_2", "00_3", "00_4", "00_4", "00_5", "00_6", "00_6", "00_7", "00_8"),
                type_id = c(3L, 4L, 6L, 7L, 2L, 6L, 3L, 2L, 6L, 5L, 2L, 1L))


event_f <- event %>%
 mutate(new_variable = id %in% (detail %>%
          filter(type_id == 6) %>%
          pull(event_id))) %>%
 collect()

Error in UseMethod("escape") : no applicable method for 'escape' applied to an object of class "c('tbl_PqConnection', 'tbl_dbi', 'tbl_sql', 'tbl_lazy', 'tbl')"

【问题讨论】:

  • 您真的在使用名为Rpostgres 的包吗? CRAN 上的那个叫RPostgres。当我使用它时,我没有收到任何错误。
  • 抱歉,这是 RPostgres。您是否尝试使用eventdetail 的远程数据帧重现上述示例?因为当它在本地时,它确实效果很好。
  • 不,我使用了您发布的示例。

标签: r dplyr dbplyr


【解决方案1】:

这个问题很可能是由嵌套的 dplyr 查询引起的。这里有两种可能:

  1. dbplyr 无法将您的查询转换为 SQL,

  2. dbplyr 会翻译您的查询,但它不是有效的 SQL。

如何分辨

dbplyr 尝试将每组命令转换为 SQL。验证这一点的一种方法是使用函数show_query()

例如 R 命令:

my_table %>% mutate(new_col = 2 * old_col + id) %>% select(new_col, id) %>% show_query()

将返回类似于以下 SQL 命令的内容:

SELECT 2 * old_col + id AS new_col, id
FROM database.my_table

这只有在 R 到 SQL 的转换已经成为可能的情况下才会发生。因此:

  1. 如果 show_query 返回 SQL,您应该检查 SQL 以确定错误的位置并调整您的 R 命令来纠正此问题

  2. 如果 show_query 没有返回,或给出错误,则 dbplyr 无法翻译您的查询,需要对其进行重组。

预计问题是由嵌套的 dplyr 命令 (detail %&gt;% filter %&gt;% pull) 引起的,我建议将其替换为 semi_join,如下所示:

detail_f <- detail %>%
    filter(type_id == 6)

event_f <- event %>%
    semi_join(detail_f, by = c("id" = "type_id")) %>%
    collect()

如果您不熟悉半联接,您可能会发现 this 的帖子很有帮助。 R 还支持使用反连接。

编辑:误读了您的初始查询。

由于您想在输出表中添加 event_id 存在/不存在的指示符,您可能可以避免半连接或反连接。可能类似于以下内容:

detail_f <- detail %>%
    filter(type_id == 6) %>%
    select(id_to_compare = event_id) %>%
    mutate(new_variable = 1)

event_f <- event %>%
    left_join(detail_f, by = c("id" = "id_to_compare")) %>%
    mutate(new_variable = ifelse(is.na(new_variable), 0, new_variable) %>%
    collect()

注意,我在这里使用了 0 和 1 而不是 FALSETRUE,因为某些版本的 SQL 不像 R 那样容易处理这些。

【讨论】:

  • 感谢您的详细回复。确实是嵌套的 dplyr 命令造成了这个问题,因为 show_query() 返回相同的错误。如果我想复制预期的输出,我必须先执行mutate(new_variable == TRUE),然后再执行anti_join()mutate(new_variable == FALSE)。我这样想对吗?
  • 不完全。我已经编辑了我的答案,以更好地复制您的预期输出。
猜你喜欢
  • 2022-12-15
  • 2023-01-22
  • 2018-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多