Search code examples
rfunctiondata.tablesublist

How can I work with sub-lists in a function in R?


I have a data table with lists and sub-list.

DT <- data.table (A=c(1,1,1,2,2,3,3,4,4,4,5), B=c(200,210,300,420,289,365,587,250,110,500,800), C=c(0.6,0.35,0.6,0.85,0.22,0.36,0.39,0.31,0.33,0.58,0.66))
DT
DT_Split <- split(DT, DT$A)
names(DT_Split) <- c(paste("FF", names(DT_Split), sep = ""))
list2env(DT_Split, .GlobalEnv)
lapply(DT_Split, function(x){
  x[, NewColumn := cumsum(c(TRUE, diff(B) < 0))]})
DT_Split2 <- lapply(DT_Split, function(x) split(x, x$NewColumn))
DT_Split2$FF1$`1`

How can I add a suffix to this sub-lists, 1 in FF1 in DT_Split2 (Last line)? How can I address this sub-list in a function?

Update I don't want to address or add a suffix manually. I mean something like this line:

names(DT_Split) <- c(paste("FF", names(DT_Split), sep = "")) 
list2env(DT_Split, .GlobalEnv)

but for sub-list.

Thanks a lot, Milad


Solution

  • You've already used this in your names(DT_Split) <- line all you need to do is access the sublist if you want to change only FF1 use the first line if you want to change all the sublists use lapply:

    # paste0 is the equivalent to paste(..., sep="") but faster
    # also no need to enclose it in c() call
    names(DT_Split2$FF1) <- paste0(names(DT_Split2$FF1) , "Suff")
    lapply(DT_Split2, function(x) {names(x)<-paste0(names(x) , "Suff"); x})
    

    to extract the names of all sublists it can be easily achieved with :

    lapply(name.of.list, names)
    #lapply(DT_Split2, names)