是否可以在dplyr中管理多个图形.
这是有效的:
birdsss = data.frame(x1 = 1:10,x2 = 21:30,x3 = 41:50)
birdsss%>%
with(hist(x1, breaks = 50))
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
birdsss%>%
with(hist(x1, breaks = 50)) %>%
with(hist(x2, breaks = 50)) %>%
with(hist(x3, breaks = 50))
Error in hist(x2, breaks = 50) : object 'x2' not found
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
birdsss%>%
with(hist(x1, breaks = 50)) &
with(hist(x2, breaks = 50)) &
with(hist(x3, breaks = 50))
Run Code Online (Sandbox Code Playgroud)
和
birdsss%>%
with(hist(x1, breaks = 50)) ;
with(hist(x2, breaks = 50)) ;
with(hist(x3, breaks = 50))
Run Code Online (Sandbox Code Playgroud)
在一行中打印多列的解决方案是什么?
就像是:
birdsss%>%
with(hist(x1:x3, breaks = 50))
Run Code Online (Sandbox Code Playgroud)
我正在使用更长的管道(filter(),select()等)以及使用多个图表完成的内容.我在这里简化了代码.
正常的%>%管道将左侧管道移到右侧.hist返回一个(非常有用的)hist对象,但它不是可以传递给另一个直方图的数据.你想要"T"管道:
library(magrittr)
birdsss %T>%
with(hist(x1, breaks = 50)) %T>%
with(hist(x2, breaks = 50)) %T>%
with(hist(x3, breaks = 50))
Run Code Online (Sandbox Code Playgroud)
这将把第一个"T"之前的任何东西输送到后来的任何东西.有关详细信息,请参阅magrittr文档.
lapply为了将上面的一些评论放到答案中,最简单的方法是对每个变量进行直方图
# let's put them in a single plot
par(mfrow = c(1, 3))
lapply(birdsss, hist, breaks = 50) # or chain into it: birdsss %>% lapply(hist, breaks = 50)
# set back to normal
par(mfrow = c(1, 1))
Run Code Online (Sandbox Code Playgroud)
但这确实搞乱了标签:
Map/mapply要用base来解决这个问题,我们需要在数据和标签上并行迭代,这可以用Map或者mapply(因为我们不关心结果 - 只有副作用 - 差别无关紧要):
par(mfrow = c(1, 3))
Map(function(x, y){hist(x, breaks = 50, main = y, xlab = y)},
birdsss,
names(birdsss))
par(mfrow = c(1, 1))
Run Code Online (Sandbox Code Playgroud)
更漂亮.但是,如果要链接到它,则需要使用它.来显示数据的去向:
birdsss %>%
Map(function(x, y){hist(x, breaks = 50, main = y, xlab = y)},
.,
names(.))
Run Code Online (Sandbox Code Playgroud)
Hadley的purrr软件包使得*apply样式循环更明显可链接(虽然不相关,更容易使用列表)而不用担心.s.在这里,由于您正在迭代副作用并希望迭代两个变量,请使用walk2:
library(purrr)
walk2(birdsss, names(birdsss), ~hist(.x, breaks = 50, main = .y, xlab = .y))
Run Code Online (Sandbox Code Playgroud)
它返回与前一个Map调用完全相同的东西(如果你设置mfrow相同的方式),尽管没有无用的输出到控制台.(如果您需要该信息,请map2改用.)请注意,迭代的参数首先出现,因此您可以轻松地链接:
birdsss %>% walk2(names(.), ~hist(.x, breaks = 50, main = .y, xlab = .y))
Run Code Online (Sandbox Code Playgroud)
在一个完全不同的方面,如果你计划最终将所有内容都放在一个单独的情节中,ggplot2可以通过它的facet_*功能使相关的情节变得非常简单:
library(ggplot2)
# gather to long form, so there is a variable of variables to split facets by
birdsss %>%
tidyr::gather(variable, value) %>%
ggplot(aes(value)) +
# it sets bins intead of breaks, so add 1
geom_histogram(bins = 51) +
# make a new "facet" for each value of `variable` (formerly column names), and
# use a convenient x-scale instead of the same for all 3
facet_wrap(~variable, scales = 'free_x')
Run Code Online (Sandbox Code Playgroud)
它看起来有点不同,但一切都是可编辑的.请注意,如果没有任何工
| 归档时间: |
|
| 查看次数: |
4873 次 |
| 最近记录: |