为什么我有时必须在`data.frame()`中附加`.`来查找`do`中的命名参数?

时间:2015-03-09 22:56:24

标签: r dplyr

为什么这不起作用?

data.frame(x = rnorm(100)) %>% do(df = .)

错误讯息:

Error in do_(.data, .dots = lazyeval::lazy_dots(...)) :
  argument ".data" is missing, with no default

相反,我必须将.括在data.frame()

data.frame(x = rnorm(100)) %>% do(df = data.frame(.))

或者,这也有效:

data.frame(x = rnorm(100)) %>% do(., df = .)

这个例子当然没有意义。但在使用data.frame时将group_by保存为列表变量会很有帮助。

这是一个似乎相关的更复杂的问题:

library("MatchIt")
n <- 5000
DF <- data.frame(
    x1 = rnorm(n),
    x2 = rbinom(n, 1, 0.5),
    group = rbinom(n, 1, 0.5),
    D = rbinom(n, 1, 0.5)) 

现在这会产生错误:

DF %>%
    group_by(group) %>%
    do(m = matchit(D ~ x1, data = ., exact = "x2"))

但是当我将.括在data.frame()中时,它会起作用:

DF %>%
    group_by(group) %>%
    do(m = matchit(D ~ x1, data = data.frame(.), exact = "x2"))

我不确定matchit的第二个示例是否相关,但在这两种情况下,我都必须将.括在data.frame()中。

sessionInfo()

> sessionInfo()
R version 3.1.1 (2014-07-10)
Platform: x86_64-apple-darwin13.4.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] MatchIt_2.4-21 MASS_7.3-33    dplyr_0.4.1    Defaults_1.1-1

loaded via a namespace (and not attached):
[1] assertthat_0.1  DBI_0.3.1       lazyeval_0.1.10 magrittr_1.5    parallel_3.1.1  Rcpp_0.11.4     tools_3.1.1

1 个答案:

答案 0 :(得分:3)

差异来自magrittr分裂链的方式。

expr1 <- substitute(data.frame(x = rnorm(100)) %>% do(df = .))
expr2 <- substitute(data.frame(x = rnorm(100)) %>% do(df = (.)))

magrittr:::split_chain(expr1)
magrittr:::split_chain(expr2)