转换为循环以应用 [英] Convert for loop to apply

查看:40
本文介绍了转换为循环以应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,如何使用applylapplyrapplydo.call等功能替换以下代码?

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和东西.

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

更新与@djhurio同时发布,它非常相似,但是我自由更改了combn的用法,因此它可以处理长度为1的u,如@ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆