给定以下数据:
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_B
、list_C
等。因此,我想避免在Map
的函数f
中调用names(list)
,因为我将不得不修改它 n 次。我正在寻找的解决方案应该适用于:Map(function(l){...}, list_A)
所以我以后可以替换
list_A
。它不必依赖Map
。 apply 中的任何一个功能会做;同样适用于 purrr基于解决方案。
替代示例
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/