简体   繁体   English

R:将 function 应用于嵌套列表

[英]R: Apply function to nested lists

I have nested lists with numeric vales.我有带有数字值的嵌套列表。 In my case they are longitudes and latitudes sorted like this:在我的情况下,它们是按如下方式排序的经度和纬度:

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)

Random numbers just for illustration purposes.随机数仅用于说明目的。 I would like to calculate the distance between two points of each nested list (list1 until list4) using the Haversine formula.我想使用 Haversine 公式计算每个嵌套列表(list1 到 list4)的两点之间的距离。 I read that it is better to avoid for loops which is why I'm looking at lapply.我读到最好避免 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)) 

This gives an error like "can't be converted to double".这会产生类似“无法转换为双精度”的错误。 I think the index is also wrong, since the function should iterate through the first list's nested lists, then go to the nested lists in the second list and so on until the 4th one.我认为索引也是错误的,因为 function 应该遍历第一个列表的嵌套列表,然后 go 到第二个列表中的嵌套列表,依此类推,直到第四个。 How can I do this?我怎样才能做到这一点? Any other (better) approach?还有其他(更好的)方法吗? Thank you!谢谢!

If your list structures match, as they do in your example, it may be simpler to unlist and then relist the data.如果您的列表结构匹配,就像在您的示例中那样,则unlist然后重新relist数据可能会更简单。 First unlist the lon/lat data and cbind to make 2-column matrices:首先unlist lon/lat 数据并cbind制作 2 列矩阵:

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

Now compute the distances and convert back to a list of the same structure:现在计算距离并转换回相同结构的列表:

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 ...

Of course, this only works if the four nested lists have the same structure.当然,这仅适用于四个嵌套列表具有相同结构的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM