Konrad
Konrad

Reputation: 18585

Getting name of an object from list in Map

Given the following data:

list_A <- list(data_cars = mtcars,
               data_air = AirPassengers,
               data_list = list(A = 1,
                                B = 2))

I would like to print names of objects available across list_A.

Example:

Map(
    f = function(x) {
        nm <- deparse(match.call()$x)
        print(nm)
        # nm object is only needed to properly name flat file that may be
        # produced within Map call
        if (any(class(x) == "list")) {
            length(x) + 1
        } else {
            length(x) + 1e6
            saveRDS(object = x,
                    file = tempfile(pattern = make.names(nm), fileext = ".RDS"))
        }
    },
    list_A
)

returns:

[1] "dots[[1L]][[1L]]"
[1] "dots[[1L]][[2L]]"
[1] "dots[[1L]][[3L]]"
$data_cars
NULL

$data_air
NULL

$data_list
[1] 3

Desired results

I would like to get:

`data_cars`
`data_air`
`data_list`

Update

Following the comments, I have modified the example to make it more reflective of my actual needs which are:


Alternative example

do_stuff <- function(x) {
    nm <- deparse(match.call()$x)
    print(nm)
    # nm object is only needed to properly name flat file that may be
    # produced within Map call
    if (any(class(x) == "list")) {
        length(x) + 1
    } else {
        length(x) + 1e6
        saveRDS(object = x,
                file = tempfile(pattern = make.names(nm), fileext = ".RDS"))
    }
}

Map(do_stuff, list_A)

As per the notes below, I want to avoid having to modify do_stuff function as I will be looking to do:

Upvotes: 2

Views: 1126

Answers (2)

moodymudskipper
moodymudskipper

Reputation: 47320

Would something like this work ?

list_A2 <- Map(list, x = list_A,nm = names(list_A) )
trace(do_stuff, quote({ nm <- x$nm;  x<- x$x}), at=3)
Map(do_stuff, list_A2)

Upvotes: 2

zx8754
zx8754

Reputation: 56189

We could wrap it into a function, and do it in two steps:

myFun <- function(myList){
  # do stuff
  res <- Map(
    f = function(x) {
      #do stuff
      head(x)
    },
    myList)

  # write to a file, here we might add control
  # if list is empty do not output to a file
  for(i in names(res)){
    write.table(res[[ i ]], file = paste0(i, ".txt"))
  }
}

myFun(list_A)

Upvotes: 4

Related Questions