Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert for loop to apply

Tags:

r

lapply

apply

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 this part:

  for (j in 1:ncol(p)) {
    s <- paste(p[,j], collapse=",")

I tried something like:

  s <- apply(p, 2, function(x) paste(x, collapse=","))

Which works. But then for that slist[[s]] <- 0 part inside that same for-loop, I don't know what to do.

Edit: 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

Yeah, I'm just trying to learn how to use apply and stuff properly.

like image 549
Crystal Avatar asked Feb 23 '23 09:02

Crystal


1 Answers

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.

like image 61
Tommy Avatar answered Feb 24 '23 22:02

Tommy