Convert for loop to apply

人盡茶涼 提交于 2019-12-03 17:35:11

Here's one solution:

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 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.

Solution using one apply and one lapply. Works also if 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

Another solution without the need for anonymous functions. The mapply vectorizes combn, while rapply traverses the combination list recursively, collapsing them using ,.

rapply(mapply(combn, list(u), seq_along(u), simplify = F), paste, collapse = ",")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!