Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading