在 lapply 期间使用 paste() 与 ggplot 和两个不同的数据源
Using paste() during lapply with ggplot and two different data sources
考虑 ggplots 列表:
list1 <- vector("list", 7)
names(list1) <- LETTERS[1:7]
list1 <- lapply(list1, function(x) {x <- ggplot(data.frame()) + geom_point() + xlim(0, 10) + ylim(0, 100);x})
我可以用
list1 <- lapply(list1, function(x) {x <- x + annotate("text", label="some text", x=4, y=4)})
在每个图中注释一些文本并用
绘制整个列表
lapply(names(list1),
function(x) ggsave(filename=paste(x,".jpg",sep=""), plot=list1[[x]]))
但是我想在每个图中注释的文本是可变的并存储在另一个向量中:
somevec <- runif(7)
所以,我需要这样的东西:
list1 <- lapply(list1, function(x) {x <- x + annotate("text", label=paste(somevec[x]), x=4, y=4);x})
但这不起作用:
Error in somevec[x] : invalid subscript type 'list'
那么,我怎样才能将 somevec
中的第 i 值粘贴到 i 的第 i 图中=18=]?
我们可以用Map
代替
out <- Map(function(x, y) x +
annotate('text', label = y, x = 4, y = 4), list1, as.character(somevec))
或者如果我们想使用lapply
,遍历序列
out <- lapply(seq_along(list1), function(i)
list1[[i]] + annotate('text', label = somevec[i], x = 4, y = 4))
你的例子中的问题是你试图将绘图用作 somevec
的索引,x
这里是一个 ggplot 图而不是像 1 或 2 这样的整数,对从 somevec
检索元素。下面的示例显示了如何使用注释
创建一个新列表
require(ggplot2)
#> Loading required package: ggplot2
list1 <- vector("list", 7)
names(list1) <- LETTERS[1:7]
list1 <- lapply(list1, function(x) {x <- ggplot(data.frame()) + geom_point() + xlim(0, 10) + ylim(0, 100);x})
somevec <- runif(7)
plist<-mapply(function(x,y){x+annotate("text", label=paste(y), x=4, y=4)}, list1, somevec, SIMPLIFY=F)
plist[[1]]
考虑 ggplots 列表:
list1 <- vector("list", 7)
names(list1) <- LETTERS[1:7]
list1 <- lapply(list1, function(x) {x <- ggplot(data.frame()) + geom_point() + xlim(0, 10) + ylim(0, 100);x})
我可以用
list1 <- lapply(list1, function(x) {x <- x + annotate("text", label="some text", x=4, y=4)})
在每个图中注释一些文本并用
绘制整个列表lapply(names(list1),
function(x) ggsave(filename=paste(x,".jpg",sep=""), plot=list1[[x]]))
但是我想在每个图中注释的文本是可变的并存储在另一个向量中:
somevec <- runif(7)
所以,我需要这样的东西:
list1 <- lapply(list1, function(x) {x <- x + annotate("text", label=paste(somevec[x]), x=4, y=4);x})
但这不起作用:
Error in somevec[x] : invalid subscript type 'list'
那么,我怎样才能将 somevec
中的第 i 值粘贴到 i 的第 i 图中=18=]?
我们可以用Map
代替
out <- Map(function(x, y) x +
annotate('text', label = y, x = 4, y = 4), list1, as.character(somevec))
或者如果我们想使用lapply
,遍历序列
out <- lapply(seq_along(list1), function(i)
list1[[i]] + annotate('text', label = somevec[i], x = 4, y = 4))
你的例子中的问题是你试图将绘图用作 somevec
的索引,x
这里是一个 ggplot 图而不是像 1 或 2 这样的整数,对从 somevec
检索元素。下面的示例显示了如何使用注释
require(ggplot2)
#> Loading required package: ggplot2
list1 <- vector("list", 7)
names(list1) <- LETTERS[1:7]
list1 <- lapply(list1, function(x) {x <- ggplot(data.frame()) + geom_point() + xlim(0, 10) + ylim(0, 100);x})
somevec <- runif(7)
plist<-mapply(function(x,y){x+annotate("text", label=paste(y), x=4, y=4)}, list1, somevec, SIMPLIFY=F)
plist[[1]]