![](/img/trans.png)
[英]Looping error with lists: for function not works inside purrr::map2 in R
[英]Use an arrow assignment function as R purrr map2
我有一個柵格列表:
filelist <- as.list(c("rasterA", "rasterB") # name them
rasterlist <- lapply(filelist, function(x) raster::raster(x)) # read them in
以及與這些柵格對應的 CRSes 列表:
crslist <- as.list(c("crsA.Rds", "crsB.Rds")) # name them
crslist %<>% lapply(function(x) readRDS(x)) # read them in
要在您使用的柵格中填充@crs
插槽(例如):
raster::crs(rasterA) <- crsA
但是我不知道如何在purrr::map2
調用中使用這個箭頭賦值。 R 備忘單中的示例是map2(x, y, sum)
,但是 sum 適用於向量,是無方向的,並且在其括號內包含它的所有術語。
閱讀 map2 幫助,我嘗試了公式格式:
purrr::map2(rasterlist, crslist, ~ raster::crs(.x) <- .y)
但沒有骰子:
as_mapper(.f, ...) 中的錯誤:object 未找到“.y”
有誰知道我會怎么做? 目前我使用的是一個簡單的循環,但我正試圖強迫自己學習映射並不斷碰到這些類型的牆。
for (i in length(rasterlist)) {
crs(rasterlist[[i]]) <- crslist[[i]]
}
謝謝!
起始條件:
for循環后:
在 raster_assigner function 之后改為:
希望這是可以挽救的,因為我還有其他類似的用例。 干杯!
我們可能需要
purrr::map2(rasterlist, crslist, ~ {crs(.x) <- .y;.x})
它與raster
無關——因為下面的簡單示例顯示了相同的錯誤
> map2(list(1, 2, 3), list(3, 4, 5), ~ names(.x) <- .y)
Error in as_mapper(.f, ...) : object '.y' not found
> map2(list(1, 2, 3), list(3, 4, 5), ~ {names(.x) <- .y; .x})
[[1]]
3
1
[[2]]
4
2
[[3]]
5
3
然而,這不會在Map
中返回錯誤(但這是不正確的,因為返回的 output 沒有名稱,除非我們用{}
包裝它並返回x
> Map(function(x, y) names(x) <- y, list(1, 2, 3), list(3, 4, 5))
[[1]]
[1] 3
[[2]]
[1] 4
[[3]]
[1] 5
可以做一個專用的 function:
raster_assigner <- function(raster, crs_input){
raster::crs(raster) <- crs_input
raster
}
purrr::map2(rasterlist, crslist, raster_assigner)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.