Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 254

7.3.4 Advanced Piping 7.3.4.1 The Dollar Pipe

Оглавление

Below we create random data that has a linear dependency and try to fit a linear model on that data.12

# This will not work, because lm() is not designed for the pipe. lm1 <- tibble(“x” = runif(10)) %>% within(y <- 2 * x + 4 + rnorm(10, mean=0, sd=0.5)) %>% lm(y ~ x) ## Error in as.data.frame.default(data): cannot coerce class ““formula”” to a data.frame

The aforementioned code fails. This is because R will not automatically add something like data = t and use the “t” as far as defined till the line before. The function lm() expects as first argument the formula, where the pipe command would put the data in the first argument. Therefore, magrittr provides a special pipe operator that basically passes on the variables of the data frame of the line before, so that they can be addressed directly: the %$%.

# The Tidyverse only makes the %>% pipe available. So, to use the # special pipes, we need to load magrittr library(magrittr) ## ## Attaching package: ‘magrittr’ ## The following object is masked from ‘package:purrr’: ## ## set_names ## The following object is masked from ‘package:tidyr’: ## ## extract lm2 <- tibble(“x” = runif(10)) %>% within(y <- 2 * x + 4 + rnorm(10, mean=0,sd=0.5)) %$% lm(y ~ x) summary(lm2) ## ## Call: ## lm(formula = y ~ x) ## ## Residuals: ## Min 1Q Median 3Q Max ## -0.6101 -0.3534 -0.1390 0.2685 0.8798 ## ## Coefficients: ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 4.0770 0.3109 13.115 1.09e-06 *** ## x 2.2068 0.5308 4.158 0.00317 ** ## --- ## Signif. codes: ## 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 ## ## Residual standard error: 0.5171 on 8 degrees of freedom ## Multiple R-squared: 0.6836,Adjusted R-squared: 0.6441 ## F-statistic: 17.29 on 1 and 8 DF, p-value: 0.003174

This can be elaborated further:

coeff <- tibble(“x” = runif(10)) %>% within(y <- 2 * x + 4 + rnorm(10, mean=0,sd=0.5)) %$% lm(y ~ x) %>% summary %>% coefficients coeff ## Estimate Std. Error t value Pr(>|t|) ## (Intercept) 4.131934 0.2077024 19.893534 4.248422e-08 ## x 1.743997 0.3390430 5.143882 8.809194e-04

The Big R-Book

Подняться наверх