转换为循环应用 [英] Convert for loop to apply
问题描述
在 R 中,如何使用 apply
、lapply
、rapply
、do.call<等函数替换以下代码/code> 等?
In R, how do you replace the following code using functions like apply
, lapply
, rapply
, do.call
, etc.?
u <- 10:12
slist <- list()
for (i in 1:length(u)) {
p <- combn(u, i)
for (j in 1:ncol(p)) {
s <- paste(p[,j], collapse=",")
slist[[s]] <- 0
}
}
对于这部分:
for (j in 1:ncol(p)) {
s <- paste(p[,j], collapse=",")
我尝试了类似的东西:
s <- apply(p, 2, function(x) paste(x, collapse=","))
哪个有效.但是对于同一 for 循环中的 slist[[s]] <- 0
部分,我不知道该怎么做.
Which works. But then for that slist[[s]] <- 0
part inside that same for-loop, I don't know what to do.
这就是我想要做的.对于向量 u
,我正在生成该向量中所有子集的列表.然后对于每个子集,我将其分配给 s
,然后使用字符串 s
作为 slist
中元素的名称.有点奇怪,我知道,但这是家庭作业.对于上面的代码,这将是 slist 的前 5 个元素:
This is what I'm trying to do. For the vector u
, I'm producing a list of all the subsets in that vector. Then for each subset, I'm assigning it to s
, then using the string s
as the name of an element in slist
. Kind of strange, I know, but it's for a homework assignment. For the code above, this would be the first 5 elements of slist:
> slist
$`10`
[1] 0
$`11`
[1] 0
$`12`
[1] 0
$`10,11`
[1] 0
$`10,12`
[1] 0
是的,我只是想学习如何正确使用 apply 和 stuff.
Yeah, I'm just trying to learn how to use apply and stuff properly.
推荐答案
这是一个解决方案:
n <- unlist(lapply(seq_along(u), function(i) {
apply(combn(length(u),i),2, function(x) paste(u[x], collapse=','))
}
))
slist <- list()
slist[n] <- 0
UPDATE 与@djhurio 同时发布,非常相似,但我冒昧更改了combn
的使用,以便处理u
长度为 1,正如@djhurio 指出的那样.
UPDATE Posted at the same time as @djhurio, it is very similar, but I took the liberty of changing the use of combn
so it handles u
of length 1, as @djhurio pointed out.
这篇关于转换为循环应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!