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

Appending missing items in a column of lists

I would like to add a 0 and 1000000, to each list in which they are missing.

dat <- structure(list(cat = structure(c(1L, 3L, 2L), levels = c("A", 
"B", "C"), class = "factor"), 
    strata = list(c(25, 100, 250, 500), c(25, 
    100, 250, 500), c(25, 100, 1000000
    ))), row.names = c(NA, -3L), class = c("data.table", "data.frame"
))

   cat                  strata
1:   A          25,100,250,500
2:   C          25,100,250,500
3:   B      25,    100,1000000

I tried to do the following:

    dat$strata <- lapply(dat$strata, \(x){
       if (0 %nin% dat$strata) {
        dat$strata<- append(0, dat$strata)
       }
       if (1000000 %nin% dat$strata) {
        dat$strata<- append(dat$strata, 1000000)
       }
    })

But I am doing something wrong.

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

Desired output:

   cat                  strata
1:   A       0,  25,100,250,500,1000000
2:   C        0, 25,100,250,500,1000000
3:   B     0, 25,    100,1000000

What is the correct syntax here?

>Solution :

An easy way is to add the 0 and 1000000 everywhere and take the unique values

dat$strata[] <- lapply(dat$strata, function(i)unique(c(0, i, 1000000)))

 dat
  cat                        strata
1   A 0, 25, 100, 250, 500, 1000000
2   C 0, 25, 100, 250, 500, 1000000
3   B           0, 25, 100, 1000000
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