"+"和"+"之间有什么区别?ggplot2中的运算符和“%"magrittr中的运算符? [英] What is the difference between the "+" operator in ggplot2 and the "%>%" operator in magrittr?
问题描述
ggplot2中的"+"
运算符与magrittr中的%>%"
运算符有什么区别?
What is the difference between the "+"
operator in ggplot2 and the "%>%"
operator in magrittr?
有人告诉我它们是相同的,但是如果考虑以下脚本.
I was told that they are the same, however if we consider the following script.
library(magrittr)
library(ggplot2)
# 1. This works
ggplot(data = mtcars, aes(x=wt, y = mpg)) + geom_point()
# 2. This works
ggplot(data = mtcars) + aes(x=wt, y = mpg) + geom_point()
# 3. This works
ggplot(data = mtcars) + aes(x=wt, y = mpg) %>% geom_point()
# 4. But this doesn't
ggplot(data = mtcars) %>% aes(x=wt, y = mpg) %>% geom_point()
推荐答案
管道与 ggplot2
的添加方式非常不同.管道运算符%>%
所做的就是将左侧的结果作为右侧的函数的第一个参数.例如:
Piping is very different from ggplot2
's addition. What the pipe operator, %>%
, does is take the result of the left-hand side and put it as the first argument of the function on the right-hand side. For example:
1:10 %>% mean()
# [1] 5.5
完全等同于 mean(1:10)
.管道对于替换多重嵌套函数(例如
Is exactly equivalent to mean(1:10)
. The pipe is more useful to replace multiply nested functions, e.g.,
x = factor(2008:2012)
x_num = as.numeric(as.character(x))
# could be rewritten to read from left-to-right as
x_num = x %>% as.character() %>% as.numeric()
但是在 R中%>%是什么意思的所有解释都很好,,您应该通读还有更多示例.
but this is all explained nicely over at What does %>% mean in R?, you should read through that for a couple more examples.
利用这些知识,我们可以将您的管道示例重新编写为嵌套函数,并看到它们仍在执行相同的操作;但现在(希望如此)很明显为什么#4不起作用:
Using this knowledge, we can re-write your pipe examples as nested functions and see that they still do the same things; but now it (hopefully) is obvious why #4 doesn't work:
# 3. This is acceptable ggplot2 syntax
ggplot(data = mtcars) + geom_point(aes(x=wt, y = mpg))
# 4. This is not
geom_point(aes(ggplot(data = mtcars), x=wt, y = mpg))
ggplot2
包括用于 ggplot
对象的特殊"+"
方法,该方法用于在绘图中添加图层.我不知道,直到您问了这个问题,它也可以与 aes()
函数一起使用,但显然也已定义好了.这些都是在 ggplot2
中专门定义的.在ggplot2中使用 +
早于管道,尽管用法相似,但功能却大不相同.
ggplot2
includes a special "+"
method for ggplot
objects, which it uses to add layers to plots. I didn't know until you asked your question that it also works with the aes()
function, but apparently that's defined as well. These are all specially defined within ggplot2
. The use of +
in ggplot2 predates the pipe, and while the usage is similar, the functionality is quite different.
作为有趣的旁注,Hadley Wickham(ggplot2的创建者)说:
As an interesting side-note, Hadley Wickham (the creator of ggplot2) said that:
...如果我较早发现管道,就永远不会有ggplot2,因为您可以将ggplot图形编写为
...if I'd discovered the pipe earlier, there never would've been a ggplot2, because you could write ggplot graphics as
ggplot(mtcars, aes(wt, mpg)) %>%
geom_point() %>%
geom_smooth()
这篇关于"+"和"+"之间有什么区别?ggplot2中的运算符和“%"magrittr中的运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!