I wonder how to get the list name or group name as a flag when using pipe operation with purrr. for example: I want to use a dynameic parameter of each list name pass to the ggsave function.
require(purrr)
require(ggplot2)
lst=list(a1=data.frame(x=1:10,y=2:11),a2=data.frame(x=1:10,y=-1*2:11))
df=rbind(transform(lst[[1]],id="a1"),transform(lst[[2]],id="a2"))
lst %>% map(~ggsave(plot=qplot(data=.,x="x",y="y",geom="line"),file=paste(listname(.),".png")))
df %>% slice_rows("id") %>%
by_slice(~ggsave(plot=qplot(data=.,x="x",y="y",geom="line"),file=paste("slicename(.)",".png")))
the slicename(.) should be something like unique(.[["id"]]), but it does not work when using slice_rows.
It is worth mentioning that using purrr::walk2
one can avoid creating a new list with lst
and names(lst)
elements:
lst=list(a1=data.frame(x=1:10,y=2:11),a2=data.frame(x=1:10,y=-1*2:11))
purrr::walk2(
lst,
names(lst),
~ ggsave(plot=qplot(data=.x,x=x,y=y,geom="line"),filename=paste(.y,".png"))
)
Updated 2017-08-30: A new family of "indexed" map functions has been introduced in purrr
0.2.3 that provide a short-hand for walk2(lst, names(lst))
:
lst=list(a1=data.frame(x=1:10,y=2:11),a2=data.frame(x=1:10,y=-1*2:11))
purrr::iwalk(
lst,
~ ggsave(plot=qplot(data=.x,x=x,y=y,geom="line"),filename=paste(.y,".png"))
)
listname
and slicename
aren't functions in purrr
and names
doesn't seem to return the list element name when used with purrr
functions. Also, you probably want to use the walk
family of functions rather than map
or by_slice
since you're calling the function for its side effects, not for the returned object.
So as a bit of workaround, you might try
lst=list(a1=data.frame(x=1:10,y=2:11),a2=data.frame(x=1:10,y=-1*2:11))
list(lst, names(lst)) %>%
pwalk( ~ ggsave(plot=qplot(data=.x,x=x,y=y,geom="line"),filename=paste(.y,".png")) )
Added
If you're starting with a data frame, you could use
df %>% split(.$id) %>%
list( names(.)) %>%
pwalk( ~ ggsave(plot=qplot(data=.x, x=x, y=y, geom="line"), filename=paste(.y,".png")))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With