我們來看下面兩段代碼:
mtcars %>%
ggplot(aes(x = cyl, y = mpg))
geom_line()
這有效并創建了以下圖:
現在讓我們看看這個:
mtcars %>%
group_by(cyl) %>%
summarise(mpg = mean(mpg))
這也有效并創建以下輸出:
# A tibble: 3 x 2
cyl mpg
<dbl> <dbl>
1 4 26.7
2 6 19.7
3 8 15.1
但是,這不起作用:
mtcars %T>%
ggplot(aes(x = cyl, y = mpg))
geom_line() %>%
group_by(cyl) %>%
summarise(mpg = mean(mpg))
它給出了以下錯誤:
Error in UseMethod("group_by") :
no applicable method for 'group_by' applied to an object of class "c('LayerInstance', 'Layer', 'ggproto', 'gg')"
為什么它不起作用?從%T>%
檔案中,我希望左側物件,在這種情況下mtcars
,將在 之后回傳ggplot
。不幸的是,這似乎不起作用。我誤解了%T>%
管道嗎?代碼應該如何使它作業?
uj5u.com熱心網友回復:
您需要將ggplot
呼叫包裝在 a 中print
,以便同時獲得兩個呼叫。您可以使用以下代碼:
library(tidyverse)
#> Warning: package 'ggplot2' was built under R version 4.1.2
#> Warning: package 'tibble' was built under R version 4.1.2
#> Warning: package 'tidyr' was built under R version 4.1.2
#> Warning: package 'readr' was built under R version 4.1.2
#> Warning: package 'dplyr' was built under R version 4.1.2
library(magrittr)
#> Warning: package 'magrittr' was built under R version 4.1.2
#>
#> Attaching package: 'magrittr'
#> The following object is masked from 'package:purrr':
#>
#> set_names
#> The following object is masked from 'package:tidyr':
#>
#> extract
mtcars %T>%
{print(ggplot(., aes(x = cyl, y = mpg))
geom_line())} %>%
group_by(cyl) %>%
summarise(mpg = mean(mpg))
#> # A tibble: 3 × 2
#> cyl mpg
#> <dbl> <dbl>
#> 1 4 26.7
#> 2 6 19.7
#> 3 8 15.1
由reprex 包于 2022-06-30 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/498316.html