如何使用lapply将列表的相对数字添加为标题

huangapple go评论77阅读模式
英文:

How to add relative number of list as title with lapply

问题

我有这个 reprex 以便让你了解我想要做什么

mtcar = mtcars[-11]
examples = list(mtcars, mtcar)

lapply(examples, function (x){
  plot(density(x$mpg), main = 
         paste0('Graph for ', ' (', ')'))
})

我希望每个图都出现在括号中,括号中显示图所代表的列表的相关编号。因此,第一个列表中的图应该在括号中显示编号 1,第二个列表中的图应该显示编号 2。

我应该如何适当地修改这段代码呢?
谢谢!

英文:

I have this as reprex to let you understand what I am trying to do

mtcar = mtcars[-11]
examples = list(mtcars, mtcar)

lapply(examples, function (x){
  plot(density(x$mpg), main = 
         paste0('Graph for ', ' (', ')'))
})

I would like each graph would appear in brackets with the related number of the list that graph is represented from. Therefore, the graph from the first list would have in the brackets number 1 and the second one, number 2.

How could I possibly properly modify the code ?
Thanks

答案1

得分: 3

使用Map而不是lapply

Map(
  function (x, i) {
    plot(density(x$mpg), main = paste0('图表 for (', i, ')'))
  },
  examples, seq_along(examples)
)
英文:

Use Map instead of lapply:

Map(
  function (x, i) {
    plot(density(x$mpg), main = paste0('Graph for (', i, ')'))
  },
  examples, seq_along(examples)
)

huangapple
  • 本文由 发表于 2023年7月6日 19:33:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76628396.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定