'How to append vectors to a list group by group
I want to add some vectors to a list, and I want to that show like this:
1.1
2.1 2
3.1 2 10
4.1 10
5.2
6.2 10
7.10
this is my code:
subsets <- function(s) {
res <- list()
n <- length(s)
s <- sort(s)
help <- function(temp, index, res) {
tmp <- temp
res <- append(res, tmp)
i <- index
while (i < n + 1 ) {
temp <- append(temp, s[i])
res <- help(temp, i + 1, res)
temp <- temp[-length(temp)]
i <- i + 1
}
return(res)
}
res <- help(c(), 1, res)
return(res)
}
s <- c(1, 10, 2)
subsets(s)
the output is:
1.1
2.1
3.2
4.1
5.2
6.10
7.1
8.10
9.2
10.2
11.10
12.10
Could somebody do me a favor? I am a new man for R, and I don't know what should I do...
Solution 1:[1]
If you want your vectors to be in a list, you can use unlist:
unlist(list)
# [1] 1 1 2 1 2 10 1 10 2 2 10 10
Or add as.list if you want everything in a list of one item:
as.list(unlist(list))
[[1]]
[1] 1
[[2]]
[1] 1
[[3]]
[1] 2
[[4]]
[1] 1
[[5]]
[1] 2
[[6]]
[1] 10
[[7]]
[1] 1
[[8]]
[1] 10
[[9]]
[1] 2
[[10]]
[1] 2
[[11]]
[1] 10
[[12]]
[1] 10
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maël |
