rlistapplynames

How to use setNames on subelements of list


I found this question but it does not seem to work for me.

The task is simple. I have a list like the following, obtained from a data frame, and I want to setNames for the subelements:

mydf <- data.frame(Patient=rep(paste0('Pat', 1:3), 2), Cycle=rep(paste0('C', 1:2), each=3))
mylist <- sapply(mydf, unique)

The list looks like:

> mylist
$Patient
[1] "Pat1" "Pat2" "Pat3"

$Cycle
[1] "C1" "C2"

The only thing I want to do is to setNames for the subelements, so that they include the element name, resulting into this final list:

> mylist
$Patient
Patient-Pat1 Patient-Pat2 Patient-Pat3 
      "Pat1"       "Pat2"       "Pat3" 

$Cycle
Cycle-C1 Cycle-C2 
    "C1"     "C2" 

Now I could go through the elements one by one like this:

mylist[[1]] <- setNames(mylist[[1]], paste(names(mylist)[1], mylist[[1]], sep='-'))
mylist[[2]] <- setNames(mylist[[2]], paste(names(mylist)[2], mylist[[2]], sep='-'))
...

But I do not want that, since the list can have variable number of elements and subelements with different names (this would go into a function that takes in different initial data frames).

Which would be the best way to accomplish this, preferably with apply functions?

My best attempt:

sapply(mylist, setNames, paste(names(mylist), mylist, sep='-'))

Solution

  • sapply(names(mylist), \(x) setNames(mylist[[x]], paste(x, mylist[[x]], sep = "-")), USE.NAMES = TRUE)
    #> $Patient
    #> Patient-Pat1 Patient-Pat2 Patient-Pat3 
    #>       "Pat1"       "Pat2"       "Pat3" 
    #> 
    #> $Cycle
    #> Cycle-C1 Cycle-C2 
    #>     "C1"     "C2"