繁体   English   中英

计算坐标R之间的距离

[英]Calculating the distance between coordinates R

我们有一组来自参与者的 50 个 csv 文件,目前被读入列表为

file_paths <- fs::dir_ls("data")
file_paths

file_contents <- list ()

for (i in seq_along (file_paths)) {
  file_contents[[i]] <- read_csv(
    file = file_paths[[i]]
  )
}

dt <- set_names(file_contents, file_paths)

我的数据如下所示:

level time     X        Y       Type
    
 1     1  355. -10.6    22.36    P
 1     1  371. -33      24.85    O
 1     2  389. -10.58   17.23    P
 1     2  402. -16.7    30.46    O 
 1     3  419. -29.41   17.32    P 
 1     4  429. -10.28   26.36    O 
 2     5  438. -26.86   32.98    P
 2     6  451. -21      17.06    O 
 2     7  463. -21      32.98    P 
 2     8  474. -19.9    17.06    O 

每个 csv 有 70 组坐标。 时间对此无关紧要,但我想在某个阶段按级别列分开。

对于每个“P”,我想将其与“O”进行比较并获得坐标之间的距离。第一个 P 将始终与第一个 O 匹配,依此类推。

现在,我将它们分成两个不同的列表,虽然这可能是完全错误的方法,但我无法弄清楚如何获取所有这些 csv 文件并获取所有这些文件的距离,列表似乎会导致大多数功能(如 dist)出现问题

到目前为止,这是我提取正确信息的方式


for (i in seq_along (dt)) {

   pLoc[[i]] <- dplyr::filter(dt[[i]], grepl("P", type)) 
   oLoc[[i]] <- dplyr::filter(dt[[i]], grepl("o", type)) 


   pX[[i]] <- pLoc[[i]] %>% pull(as.numeric(headX)) 
   pY[[i]] <- pLoc[[i]] %>% pull(as.numeric(headY)) 
    
   pCoordinates[[i]] <- cbind(pX[[i]], pY[[i]])
}

[编辑] 在评论之后,您可以使用栅格库执行以下操作:

library(raster)
library(dplyr)

df = data.frame(
  x = c(10, 20 ,15,9),
  y = c(45,34,54,24),
  type = c("P","O","P","O")
)

df = cbind(df[df$type=="P",]  %>% 
             dplyr::select(-type) %>% 
             dplyr::rename(xP = x,
                    yP = y),
           df[df$type=="O",] %>% 
             dplyr::select(-type) %>% 
             dplyr::rename(xO = x,
                    yO = y))

使用某种形式的apply() function 可能更有效地实现以下目标:

v = c()

for(i in 1:nrow(df)){
  
  dist = raster::pointDistance(lonlat = F,
                               p1 = c(df$xP[i],df$yP[i]),
                               p2 = c(df$xO[i],df$yO[i]))
  
  v = c(v,dist)
  
}

df$dist = v

print(df)
xP yP xO yO     dist
1 10 45 20 34 14.86607
3 15 54  9 24 30.59412

暂无
暂无

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

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