我正在根据两个列表中的数据生成和绘制多个‘m图,因此我使用的是mapply。其中一个列表指定了元素,我想将其用作ggtitle。但是对于所有的情节,它只需要第一个元素
> names(sample_subset_list)
[1] "water after day 43 dna min reads per OTU 5"
[2] "biofilm after day 43 dna min reads per OTU 5"
[3] "water after day 43 cdna min reads per OTU 5"
[4] "biofilm after day 43 cdna min reads per OTU 5"
[5] "water after day 44 dna min reads per OTU 5"
[6] "biofilm after day 44 dna min reads per OTU 5"
[7] "water after day 44 cdna min reads per OTU 5"
[8] "biofilm after day 44 cdna min reads per OTU 5"这是绘图功能:
ordination_plots <- list()
counter <- 0
ordination_plots <- mapply(function(x,y,counter) {
counter <- counter + 1
plot_ordination(x, y, type = "sample") +
ggtitle(names(sample_subset_list)[counter]) +
}, x = sample_subset_list, y = ordination_nmds, counter = 0, SIMPLIFY = FALSE)这将给出标题总是第一个元素的情节。
names(sample_subset_list)。
调用ggtitle(names(sample_subset_list)[]) +也会发生同样的情况
如果我使用counter <<- (这里建议使用:Using a counter inside an apply structured loop in R)或调用ggtitle,如
ggtitle(names(sample_subset_list)) +
或
ggtitle(names(sample_subset_list)[[]]) +
我根本没有头衔。
我一开始没有一个计数器,这也给了我同样的标题所有的情节。有人能向我解释一下,我如何可以迭代列表元素的名称,以便将它们用于gg夜图吗?
发布于 2018-11-23 15:13:08
让我们降低示例的复杂性:
counter <- 0
invisible(mapply(function(letter, counter) {
counter <- counter + 1
cat("Letter: ", letter, "; Counter: ", counter, "\n", sep="")
}, letters[1:10], counter))注意:我只使用invisible()来停止打印mapply()的结果。
letters[1:10]是小写字母的10元素向量(内置于数据中)。
您可以在counter之外定义mapply()。与for或while不同,mapply()中的函数不--默认情况下不修改父作用域中的- create或修改变量( mapply()之外),因此结果如下:
Letter: a; Counter: 1
Letter: b; Counter: 1
Letter: c; Counter: 1
Letter: d; Counter: 1
Letter: e; Counter: 1
Letter: f; Counter: 1
Letter: g; Counter: 1
Letter: h; Counter: 1
Letter: i; Counter: 1
Letter: j; Counter: 1向mapply()的函数参数传递包含信息的第二个参数是可以的,但是如果目的是在mapply()函数的作用域之外增加某些内容的副作用,那么就不应该将它作为参数传递给它,而只是使用<<-操作符来修改它,该操作符是- according到帮助页面:
运算符<<-和->>通常只在函数中使用,并导致在父环境中搜索分配变量的现有定义。如果找到这样的变量(且绑定未锁定),则重新定义其值,否则将在全局环境中进行赋值。
所以,我们可以这么做
# TO MY FUTURE SELF AND TEAM MEMBERS
# `counter` is modified as a side-effect of operations in the `mapply()`
# that follows the object declaration
counter <- 0
invisible(mapply(function(letter) {
counter <<- counter + 1
cat("Letter: ", letter, "; Counter: ", counter, "\n", sep="")
}, letters[1:10]))为了得到这个:
Letter: a; Counter: 1
Letter: b; Counter: 2
Letter: c; Counter: 3
Letter: d; Counter: 4
Letter: e; Counter: 5
Letter: f; Counter: 6
Letter: g; Counter: 7
Letter: h; Counter: 8
Letter: i; Counter: 9
Letter: j; Counter: 10这句话并不是用来咆哮的。你正在使用的副作用可能对你未来的自我或与你共享代码的人来说并不明显,因此注意到它将帮助你重新理解,让他们知道发生了什么。
https://stackoverflow.com/questions/53448884
复制相似问题