简体   繁体   English

如何在 r 中使用列表元素作为 plot 标题?

[英]How to use list elements as plot title in r?

I have this kind of data:我有这样的数据:

d<- list(d1 = list(`1979` = 3.8234619080332, `1980` = 3.94835997755299, 
    `1981` = 4.40780893307071), d2 = list(`1979` = 3.78682062013644, 
    `1980` = 3.89720895853959, `1981` = 4.35137469930167))

I am trying to plot my data and I want to use the list names d1 and d2 as plot titles.我正在尝试 plot 我的数据,我想使用列表名称d1d2作为 plot 标题。

I have tried this function with lapply;我用 lapply 试过这个 function;

fun1<-function(x) {
  y<-x
  x<-unlist(x)
  plot(ecdf(x), main=deparse(substitute(y)))
  }

lapply(d, fun1)

What I got are:我得到的是:

在此处输入图像描述

在此处输入图像描述

But I want to see d1 for the first plot and d2 for the second plot as the main title name instead of "list(d1 = list( 1979 = 3.823461...."但我想看到第一个 plot 的 d1 和第二个 plot 的 d2 作为主标题名称,而不是“list(d1 = list( 1979 = 3.823461....”

You could use mapply to loop over both d and names(d) to pass the name of the list element to your function:您可以使用mapply循环遍历dnames(d)以将列表元素的名称传递给您的 function:

d<- list(d1 = list(`1979` = 3.8234619080332, `1980` = 3.94835997755299, 
                   `1981` = 4.40780893307071), d2 = list(`1979` = 3.78682062013644, 
                                                         `1980` = 3.89720895853959, `1981` = 4.35137469930167))

fun1<-function(x, y) {
  plot(ecdf(unlist(x)), main=y)
}

mapply(fun1, d, names(d))

You could include the lapply() in your function and use the names() .您可以在 function 中包含lapply()并使用names()

fun1 <- function(d) {
  nm <- names(d)
  lapply(nm, function(i) plot(ecdf(unlist(d[[i]])), main=i))
}

op <- par(mfrow=c(1, 2))
fun1(d)
par(op)

在此处输入图像描述

Using purrr::imap -使用purrr::imap -

fun1<-function(x, y) {
  plot(ecdf(unlist(x)), main=y)
}

purrr::imap(d, fun1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM