user88911 user88911 - 3 months ago 19
R Question

How to make named data.frame object in the list instead of using default numeric index?

I wrote my custom function for performing setdiff operation for list of data.frame object recursively. Now my custom function return list of unnamed data.frame object. However, I want each data.frame in each list must have name with very specific order. I aware that few changes must be needed in my custom function in order to return named data.frame object in each list. I tried to assign name for them, but that was not elegant to do. How can I get my expected output ? Can anyone propose possible idea to fix and improve the code in custom function ? FYI, all data, custom function, desired output are simulated.

data:

myList <- list(
foo = data.frame( start=seq(1, by=4, len=6), stop=seq(3, by=4, len=6)),
bar = data.frame(start=seq(5, by=2, len=7), stop=seq(7, by=2, len=7)),
bleh = data.frame(start=seq(1, by=5, len=5), stop=seq(3, by=5, len=5))
)


I coded this custom function :

library(dplyr)

func <- function(list, idx=1L) {
entry <- list[[idx]]
self_ <- setdiff(entry, entry)
res <- lapply(list[-idx], function(ele_) {
joined_ <- setdiff(entry, ele_)
joined_
})
result <- c(list(self_), res)
return(result)
}


output of my custom function are:

res_1 <- func(list = myList, idx = 1L)
res_2 <- func(list = myList, idx = 2L)
res_3 <- func(list = myList, idx = 3L)


I expect my custom function must explicitly indicate name of data.frame in each list by very different order instead of default numeric index.

desired output:

res_1 <- list(foo=data.frame(), bar=data.frame(), bleh=data.frame())
res_2 <- list(bar=data.frame(), foo=data.frame(), bleh=data.frame())
res_3 <- list(bleh=data.frame(), foo=data.frame(), bar=data.frame())


How can I achieve my desired output? Is there any smart way to fix the problem in my custom function? How can I make this happen? Thanks a lot

Answer

As the other commentators have pointed out, you need to use an = rather than an <- to assign named elements to your list, ie

myList <- list(
  foo = data.frame( start=seq(1, by=4, len=6), stop=seq(3, by=4, len=6)),
  bar = data.frame(start=seq(5, by=2, len=7), stop=seq(7, by=2, len=7)),
  bleh = data.frame(start=seq(1, by=5, len=5), stop=seq(3, by=5, len=5))
)

Once you have done that you can get the results you want by adding one line to your function

func <- function(list, idx=1L) {
    entry <- list[[idx]]
    self_ <- setdiff(entry, entry)
    res <- lapply(list[-idx], function(ele_) {
        joined_ <- setdiff(entry, ele_)
    })
    result <- c(list(entry), res)
    names(result) <- c(names(list[idx]),names(list[-idx]))
    return(result)
}
Comments