我努力添加数据框的名称以绘制多个图。
这是示例数据。
df<-structure(list(d1 = structure(list(lists..1.. = c(43L, 64L, 55L,
52L, 56L, 68L, 33L, 15L, 10L, 62L, 3L, 51L, 16L, 80L, 48L, 6L,
58L, 38L, 91L, 76L, 95L, 32L, 17L, 45L)), .Names = "lists..1..", row.names = c(NA,
-24L), class = "data.frame"), d2 = structure(list(lists..2.. = c(100L,
67L, 84L, 93L, 8L, 22L, 38L, 71L, 76L, 99L, 31L, 18L, 5L, 48L,
25L, 68L, 94L, 81L, 36L, 45L, 56L, 34L, 74L, 44L)), .Names = "lists..2..", row.names = c(NA,
-24L), class = "data.frame")), .Names = c("d1", "d2"))
和示例函数:
fun<- function(x) {
h1<-max(x)
h2<-min(x)
plot(h1, h2)
pname <-lapply(x, function(x) (paste(unique(sub("\\.\\d+$", "", names(x))))))
mtext(pname,side=3,padj=2)
}
我用过
out<-lapply(df, fun)
如您所见,标题是 character(0)
对于两个数据框。但我想要的是看到 d1
和 d2
分别为每个地 block 。
最佳答案
lapply
不传递列表的名称。一种方法是使用 Map
并分别传递名称。
fun <- function(x, y) {
h1<-max(x)
h2<-min(x)
plot(h1, h2)
pname <- sub("\\.\\d+$", "", y)
mtext(pname,side=3,padj=2)
}
Map(fun, df, names(df))
purrr
imap
也可以实现同样的效果
purrr::imap(df, fun)
如果你仍然想使用lapply
,你可以将索引子集传递给函数中的数据
fun<- function(x) {
h1<-max(df[[x]])
h2<-min(df[[x]])
plot(h1, h2)
pname <- sub("\\.\\d+$", "", names(df)[x])
mtext(pname,side=3,padj=2)
}
lapply(seq_along(df), fun)
关于r - 添加数据框名称以在 R 中使用 lapply 进行绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59083346/