Piping histograms in dplyr (R) -
is possible pipe multiple graphs in dplyr.
this working:
birdsss = data.frame(x1 = 1:10,x2 = 21:30,x3 = 41:50) birdsss%>% with(hist(x1, breaks = 50))
but not working:
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
i've tried:
birdsss%>% with(hist(x1, breaks = 50)) & with(hist(x2, breaks = 50)) & with(hist(x3, breaks = 50))
and
birdsss%>% with(hist(x1, breaks = 50)) ; with(hist(x2, breaks = 50)) ; with(hist(x3, breaks = 50))
what solution print multiple columns in 1 line?
something like:
birdsss%>% with(hist(x1:x3, breaks = 50))
i'm using longer pipe (filter(), select(), etc.) , finish multiple graph. simplified code here.
lapply
to put of comments above answer, simplest way make histogram of each variable is
# let's put them in single plot par(mfrow = c(1, 3)) lapply(birdsss, hist, breaks = 50) # or chain it: birdsss %>% lapply(hist, breaks = 50) # set normal par(mfrow = c(1, 1))
this mess labels, though:
map
/mapply
to fix base, we'd need iterate in parallel on data , labels, can done map
or mapply
(since don't care results—only side effects—the difference doesn't matter):
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))
much prettier. however, if want chain it, you'll need use .
show data supposed go:
birdsss %>% map(function(x, y){hist(x, breaks = 50, main = y, xlab = y)}, ., names(.))
purrr
hadley's purrr
package makes *apply
-style looping more chainable (and though unrelated, working lists easier) without worrying .
s. here, since you're iterating side-effects , want iterate on 2 variables, use walk2
:
library(purrr) walk2(birdsss, names(birdsss), ~hist(.x, breaks = 50, main = .y, xlab = .y))
which returns exact same thing previous map
call (if set mfrow
same way), though without useless output console. (if want information, use map2
instead.) note parameters iterate on come first, though, can chain:
birdsss %>% walk2(names(.), ~hist(.x, breaks = 50, main = .y, xlab = .y))
ggplot
on different tack, if you're planning on sticking in single plot anyway, ggplot2 makes making related plots easy facet_*
functions:
library(ggplot2) # gather long form, there variable of variables split facets birdsss %>% tidyr::gather(variable, value) %>% ggplot(aes(value)) + # sets bins intead of breaks, add 1 geom_histogram(bins = 51) + # make new "facet" each value of `variable` (formerly column names), , # use convenient x-scale instead of same 3 facet_wrap(~variable, scales = 'free_x')
it looks bit different, editable. note nice labels without work.
Comments
Post a Comment