引用变量的奇怪行为

Strange behaviour referring to variables

我在引用表中的变量时使用 dplyr 看到了一些奇怪的行为。也许我需要以不同的方式处理这个问题,或者这可能是一个错误。也许你能帮帮我!

这个有效:

data <- data.frame(x = 1:10)
data <- as.tbl(data)
cut(data$x, breaks = 2)

[1] (0.991,5.5] (0.991,5.5] (0.991,5.5] (0.991,5.5] (0.991,5.5] (5.5,10]   
[7] (5.5,10]    (5.5,10]    (5.5,10]    (5.5,10]   
Levels: (0.991,5.5] (5.5,10]

这不是:

cut(data[, "x"], breaks = 2)
Error in cut.default(data[, "x"], breaks = 2) : 'x' must be numeric

这可能与dplyr中使用的非标准评估有关。有什么想法吗?

谢谢

大卫

所以要关闭它,请查看 source code, it seems that [.tbl_df (unlike [.data.frame) alsways sets drop = FALSE and doesn't let you 以其他方式告诉它

所以当你

data[, "x"]

What actually happens

result <- .subset(data, "x")
class(result) <- c("tbl_df", "data.frame")
attr(result, "row.names") <- .set_row_names(nrow(data))
result

而您实际寻找的是

.subset(data, "x")[[1]]

(如果lnegth(j) == 1L

正如评论中提到的,这已经在讨论中here