给出以下数据:
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_A
时,我正在对列表的每个元素执行一些操作除了list_A
外,还有list_B
,list_C
等。因此,我要避免在names(list)
的函数f
中调用Map
,因为我将不得不对其进行 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_...)
答案 0 :(得分:4)
我们可以将其包装为一个函数,并分两步进行:
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)
答案 1 :(得分:2)
这样的作品会吗?
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)