簡體   English   中英

R:將 function 應用於嵌套列表

[英]R: Apply function to nested lists

我有帶有數字值的嵌套列表。 在我的情況下,它們是按如下方式排序的經度和緯度:

list1 <- list(1:50, 1:25, 1:30)
list2 <- list(1:50, 1:25)
list3 <- list(1:30)
list4 <- list(1:50, 1:25, 1:30, 1:45)
nested_lons1 <- list(list1, list2, list3, list4) 
nested_lons2 <- list(list1, list2, list3, list4) 
nested_lats1 <- list(list1, list2, list3, list4) 
nested_lats2 <- list(list1, list2, list3, list4)

隨機數僅用於說明目的。 我想使用 Haversine 公式計算每個嵌套列表(list1 到 list4)的兩點之間的距離。 我讀到最好避免 for 循環,這就是我關注 lapply 的原因。

dist <- lapply(1:4, function(x) distHaversine(c(nested_lons1[x],nested_lats1[x]),
                                              c(nested_lons2[x],nested_lats2[x]), r = 6371)) 

這會產生類似“無法轉換為雙精度”的錯誤。 我認為索引也是錯誤的,因為 function 應該遍歷第一個列表的嵌套列表,然后 go 到第二個列表中的嵌套列表,依此類推,直到第四個。 我怎樣才能做到這一點? 還有其他(更好的)方法嗎? 謝謝!

如果您的列表結構匹配,就像在您的示例中那樣,則unlist然后重新relist數據可能會更簡單。 首先unlist lon/lat 數據並cbind制作 2 列矩陣:

library(geosphere)
p1 <- cbind(unlist(nested_lons1), unlist(nested_lats1))
p2 <- cbind(unlist(nested_lons2), unlist(nested_lats2))

現在計算距離並轉換回相同結構的列表:

d12 <- distHaversine(p1, p2)
d12.lst <- relist(d12, nested_lons1)
str(d12.lst)
# List of 4
#  $ :List of 3
#   ..$ : num [1:50] 0 0 0 0 0 0 0 0 0 0 ...
#   ..$ : num [1:25] 0 0 0 0 0 0 0 0 0 0 ...
#   ..$ : num [1:30] 0 0 0 0 0 0 0 0 0 0 ...
#  $ :List of 2
#   ..$ : num [1:50] 0 0 0 0 0 0 0 0 0 0 ...
#   ..$ : num [1:25] 0 0 0 0 0 0 0 0 0 0 ...
#  $ :List of 1
#   ..$ : num [1:30] 0 0 0 0 0 0 0 0 0 0 ...
#  $ :List of 4
#   ..$ : num [1:50] 0 0 0 0 0 0 0 0 0 0 ...
#   ..$ : num [1:25] 0 0 0 0 0 0 0 0 0 0 ...
#   ..$ : num [1:30] 0 0 0 0 0 0 0 0 0 0 ...
#   ..$ : num [1:45] 0 0 0 0 0 0 0 0 0 0 ...

當然,這僅適用於四個嵌套列表具有相同結構的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM