7

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.

mbask
  • 2,471
  • 18
  • 17
earclimate
  • 375
  • 1
  • 14

2 Answers2

6

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"))
)
mbask
  • 2,471
  • 18
  • 17
5

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")))
WaltS
  • 5,410
  • 2
  • 18
  • 24
  • Thanks! So is it the best way for a grouped data.frame: `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")) df %>% split(.[["id"]]) %>% list(.,as.character(unique(df[["id"]]))) %>% pwalk( ~ ggsave(plot=qplot(data=.x,x=x,y=y,geom="line"),filename=paste(.y,".png")))` – earclimate Jan 18 '16 at 01:16
  • if the unique(df[["id"]]) is a factor rather than a character class, the result is different (1.png, 2.png), maybe this is a bug. – earclimate Jan 18 '16 at 01:20