r - 使用 magrittr tee %T>% 运算符会产生错误

标签 r ggplot2 dplyr

我正在尝试创建两个图:一个是整个数据集,另一个是按“站点”分组因子拆分时的平均图。

这是源数据:

site.data <- structure(list(site = structure(c(1L, 1L, 1L, 1L,1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L), 
.Label = c("ALBEN", "ALDER", "AMERI"), class = "factor"),  
year = c(5L, 10L, 20L, 50L, 100L, 200L, 500L, 5L, 10L, 20L, 50L, 100L, 200L, 500L, 5L, 10L, 20L, 50L, 100L, 200L),
peak = c(101529.6, 117483.4, 132960.9, 153251.2, 168647.8, 184153.6, 204866.5, 6561.3, 7897.1, 9208.1, 10949.3,12287.6, 13650.2, 15493.6, 43656.5, 51475.3, 58854.4, 68233.3, 75135.9, 81908.3)),
.Names = c("site", "year","peak"), class = "data.frame", row.names = c(NA, -20L))  

这是我当前的代码:
library(ggplot2)
library(dplyr)
library(magrittr)

site.data %T>%     

           # then use a tee operator to plot the graph               
ggplot(aes(year, peak, color = site)) + geom_line() + geom_point(size = 6)   %>%

           # then group by the site  
group_by(site) %>%  

           # and finally create a graph of the mean values
summarize(mean = mean(peak)) %>%
ggplot(aes(site, mean, color = site)) + geom_point(size = 6)

但我收到此错误消息:
“as.vector(x, mode) 中的错误:无法将类型‘环境’强制转换为‘任何’类型的向量”

现在,如果我用常规的 magrittr 管道运算符替换 tee 运算符并注释掉第一个 ggplot 行,那么至少我得到第二个 ggplot,如下所示:
site.data %>%                                 
   #   ggplot(aes(year, peak, color = site)) + geom_line() + geom_point(size = 6)   %>%
group_by(site) %>%
summarize(mean = mean(peak)) %>%
ggplot(aes(site, mean, color = site)) + geom_point(size = 6)

有什么建议么?谢谢

最佳答案

这是操作顺序很重要的情况。 %%运算符的绑定(bind)比 + 更紧密做。所以当你说

site.data %T>% ggplot(aes(year, peak, color = site)) + geom_line() 

这和
( site.data %T>% ggplot(aes(year, peak, color = site)) ) + geom_line() 

这基本上是在做
site.data + geom_line()

它返回您得到的相同错误。您需要将所有 ggplot 图层添加/修改明确分组到一个代码块中。尝试
site.data %T>%     
{print(ggplot(., aes(year, peak, color = site)) + geom_line() + geom_point(size = 6))}  %>%
group_by(site) %>%  
summarize(mean = mean(peak)) %>%
{ggplot(., aes(site, mean, color = site)) + geom_point(size = 6)}

关于r - 使用 magrittr tee %T>% 运算符会产生错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28665697/

相关文章:

r - 如何根据另一个数据框中的多个列值进行过滤?

r - 将 dplyr `filter()` 的过滤器存储在变量中

r - 按列和按行进行子集化?

r - 什么是 %||% 运算符(在 ggplot2 中使用),它在哪里定义?

r - dplyr 和 ggplot 管道未按预期工作

r - 使用 dplyr 过滤数据帧后,从因子中删除未使用的级别

r - 如何根据另一列的值重命名嵌套小标题中的列

r - 如何使用ddply按组对数据进行子采样?

r - 更改厚度中线 geom_boxplot()

r - 将方程添加到绘图上的回归线