gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:16:29 24 4
gpt4 key购买 nike

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

这是源数据:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com