【发布时间】:2018-12-13 14:51:11
【问题描述】:
给定以下数据:
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`
更新
在 cmets 之后,我修改了示例,使其更能反映我的实际需求,即:
- 在使用
Map迭代list_A时,我正在对列表的每个元素执行一些操作 - 我想定期创建一个平面文件,其名称反映已处理对象的名称
-
除了
list_A,还有list_B、list_C等等。因此,我想避免在Map的函数f中调用names(list),因为我将不得不修改它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_...)
【问题讨论】:
-
names(list_A)有什么问题? -
我不清楚为什么
names(list_A)不适合您。你能建立一个更好的例子来说明原因吗? -
您是在问如何遍历名称和数据?如果是这种情况,您可以使用
purrr::map2(list_A, names(list_A), ~ .y)并通过.x访问相应的数据元素。如果这不是您要找的东西,我也很困惑为什么names(list_A)不是您要找的东西。 -
@MHammer 我还认为 OP 可能想要迭代
list_A保留名称。当base解决方案等效时,我只是建议避免使用外部包(尤其是具有大量依赖项的purrrr)。例如Map(function(x,y) dosomethingWithNamesAndValues, list_A, names(list_A)). -
Map不会传递列表元素的名称。所以我同意你可能需要做类似do_stuff <- function(x, nm) { do stuff }; Map(do_stuff, list, names(list)).
标签: apply purrr r list function mapping