rr-rownames

How to set row names for inner levels in a nested list?


In the nested list below, I need to set row names to resource and the row names should be taken from bodyPart. I want this to be applied to all objects (e.g., obj1, obj2)

obj1 <- list(resource = list(bodyPart = c("leg", "arm", "knee"),side = c("LEFT", "RIGHT", "LEFT"), device = c("LLI", "LSM", "GHT")), cat = list(lab = c("aa", "bb", "cc")))
obj2 <- list(resource = list(bodyPart = c("leg", "arm", "knee"), side = c("LEFT", "LEFT", "LEFT"), device = c("GOM", "LSM", "YYY")))

x <- list(foo = c(fer = "wdb", obj1), bar = obj2)

I would like the output to look like this at resource level, for instance for obj2.

bodyPart side device
leg leg LEFT GOM
arm arm LEFT LSM
knee knee LEFT YYY

I appreciate your edvice.


Solution

  • Edited to make it a double-lapply:

    lapply(x, function(y) {
      lapply(y, function(z) {
        if ("bodyPart" %in% names(z)) {
          `rownames<-`(as.data.frame(z), z[["bodyPart"]])
        } else z
      )
    )
    # $foo
    # $foo$fer
    # [1] "wdb"
    # $foo$resource
    #      bodyPart  side device
    # leg       leg  LEFT    LLI
    # arm       arm RIGHT    LSM
    # knee     knee  LEFT    GHT
    # $foo$cat
    # $foo$cat$lab
    # [1] "aa" "bb" "cc"
    # $bar
    # $bar$resource
    #      bodyPart side device
    # leg       leg LEFT    GOM
    # arm       arm LEFT    LSM
    # knee     knee LEFT    YYY