How to get list name and slice name with pipe and purrr

孤者浪人 提交于 2019-12-05 08:03:59

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

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"))
)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!