代码之家  ›  专栏  ›  技术社区  ›  Konrad

从映射中的列表中获取对象的名称

  •  1
  • Konrad  · 技术社区  · 7 年前

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

    我想打印可用于 list_A

    例子:

    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
    )
    

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

    我想得到:

    `data_cars`
    `data_air`
    `data_list`
    

    • 使用时 Map 我正在对列表中的每个元素执行一些操作
    • 列表 list_B ,请 list_C 等等。因此,我不想打电话 names(list) 在函数内部 f 地图 因为我必须修改它 N号 次数。我正在寻找的解决方案应该是:

      Map(function(l){...}, list_A)
      

      所以我以后可以换 列表 .它不必依赖 地图 .任何 函数可以;同样适用于 -基于解决方案。


    其他示例

    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)
    

    根据下面的注释,我想避免修改 do_stuff 正如我所期待的那样:

    • Map(do_stuff, list_A)
    • Map(do_stuff, list_B)
    • Map(do_stuff, list_...)
    2 回复  |  直到 7 年前
        1
  •  2
  •   moodymudskipper    7 年前

    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)
    
        2
  •  4
  •   zx8754    7 年前

    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)