当前位置: 动力学知识库 > 问答 > 编程问答 >

r - Why do I sometimes have to enclose `.` in `data.frame()` for a named argument in `do`?

问题描述:

Why does this not work?

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

Error message:

Error in do_(.data, .dots = lazyeval::lazy_dots(...)) :

argument ".data" is missing, with no default

Instead, I have to enclose the . in data.frame():

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

Alternatively, this also works:

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

The example, of course, doesn't make sense. But it can be helpful to save the data.frame as a list variable when working with group_by.

Here is a more complex problem that seems to be related:

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))

Now this produces an error:

DF %>%

group_by(group) %>%

do(m = matchit(D ~ x1, data = ., exact = "x2"))

But it works when I enclose the . in data.frame():

DF %>%

group_by(group) %>%

do(m = matchit(D ~ x1, data = data.frame(.), exact = "x2"))

I am not sure whether the second example with matchit is related but in both cases I have to enclose the . in 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

网友答案:

The difference comes from the magrittr way of splitting chains.

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)
分享给朋友:
您可能感兴趣的文章:
随机阅读: