How to get list name and slice name with pipe and

2019-06-23 16:15发布

问题:

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.

回答1:

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")))


回答2:

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"))
)