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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With