r - 从 map 中的列表中获取对象的名称

标签 r list function mapping

给定以下数据:

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`

更新

根据评论,我修改了示例以使其更能反射(reflect)我的实际需求:

  • 在使用 Map 遍历 list_A 时,我正在对列表的每个元素执行一些操作
  • 我想定期创建一个平面文件,其名称反射(reflect)已处理对象的名称
  • 除了list_A,还有list_Blist_C等。因此,我想避免在 Map 的函数 f 中调用 names(list),因为我将不得不修改它 n 次。我正在寻找的解决方案应该适用于:

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

    所以我以后可以替换 list_A。它不必依赖 Map 中的任何一个功能会做;同样适用于 基于解决方案。


替代示例

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_...)

最佳答案

我们可以将它包装成一个函数,分两步完成:

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)

关于r - 从 map 中的列表中获取对象的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51185934/

相关文章:

r - 最高观察结转

r - 在R中找到桌面路径

c - 如何让这个C程序在不修改代码的情况下调用这个函数?

java - 在 JSP 中获取 Map<String, List<String>> 中列表的第一个元素

list - Python __init__ 函数的变量标识 - 谁能解释一下?

javascript - 如何仅使用 pop 删除特定索引处的数组元素?

javascript - 函数中的返回语句

r - data.table 使用 setDT 修改父环境/奇怪的行为

r - 更改 ggpairs 中的对角线图

java 8 : Change value inside stream