Home > Enterprise >  Appending missing items in a column of lists
Appending missing items in a column of lists

Time:06-28

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.

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?

CodePudding user response:

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
  • Related