4

在 R 中,如何使用 、 、 、 等函数apply替换lapply以下rapply代码do.call

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=","))

哪个有效。但是对于slist[[s]] <- 0同一个 for 循环中的那部分,我不知道该怎么做。

编辑:这就是我想要做的。对于向量u,我正在生成该向量中所有子集的列表。然后对于每个子集,我将其分配给s,然后将字符串s用作 中元素的名称slist。有点奇怪,我知道,但这是为了家庭作业。对于上面的代码,这将是 slist 的前 5 个元素:

 > slist
 $`10`
 [1] 0

 $`11`
 [1] 0

 $`12`
 [1] 0

 $`10,11`
 [1] 0

 $`10,12`
 [1] 0

是的,我只是想学习如何正确使用 apply 和 stuff。

4

3 回答 3

4

这是一个解决方案:

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

更新与@djhurio同时发布,它非常相似,但我冒昧地更改了使用,combn因此它处理u长度为1,正如@djhurio指出的那样。

于 2011-11-15T21:30:22.717 回答
3

使用 oneapply和 one的解决方案lapply。如果length(u)==1.

# Define function to create combinations
f1 <- function(y, i) {
  if (length(y)==1) as.character(y) else {
    p <- combn(y, i)
    apply(p, 2, function(x) paste(x, collapse=","))
  }
}

# Initial vector
u <- 10:12

# Character vector with all posible combinations
l <- unlist(lapply(1:length(u), f1, y=u))
l

# Create list with 0 values and same length as l
slist <- as.list(rep(0, length(l)))

# Assign names to the list objects
names(slist) <- l

slist
于 2011-11-15T21:29:24.323 回答
1

另一种不需要匿名函数的解决方案。向mapply量化combn,同时rapply递归地遍历组合列表,使用 . 折叠它们,

rapply(mapply(combn, list(u), seq_along(u), simplify = F), paste, collapse = ",")
于 2011-11-15T22:53:44.907 回答