如何使用pipe和purrr获取列表名称和切片名称

时间:2016-01-17 03:01:27

标签: r ggplot2 pipe purrr

我想知道在使用purrr管道操作时如何将列表名称或组名称作为标志。例如:我想使用每个列表名称的dynameic参数传递给ggsave函数。

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

slicename(。)应该是唯一的(。[[“id”]]),但在使用slice_rows时它不起作用。

2 个答案:

答案 0 :(得分:4)

值得一提的是,使用@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // run the code making use of getActivity() from here } 可以避免使用purrr::walk2lst元素创建新列表:

names(lst)

更新2017-08-30 :一个全新的"索引" 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")) ) 0.2.3中的地图函数introducedpurrr提供了简写:

walk2(lst, names(lst))

答案 1 :(得分:3)

listname中的{p> slicenamepurrr功能并不names purrr与{{1}一起使用时似乎没有返回列表元素名称}} 功能。此外,您可能希望使用walk系列函数而不是mapby_slice,因为您正在调用函数的副作用,而不是返回的对象。< / p>

作为一些解决方法,您可以尝试

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

<强>加

如果您从数据框开始,可以使用

df %>% split(.$id) %>% 
       list( names(.)) %>% 
       pwalk( ~ ggsave(plot=qplot(data=.x, x=x, y=y, geom="line"), filename=paste(.y,".png")))