如何在R中的数据帧中的每个可能的行组合上应用几个函数?

问题描述 投票:3回答:2

我有一个坐标为(lon,lat)的数据框

    lon <- list(505997.627175236, 505997.627175236, 505997.627175236, 505997.627175236)   
    lon <- do.call(rbind.data.frame, lon)

    lat <- list(7941821.025438220, 7941821.025438220, 7941821.025438220, 7941821.025438220)
    lat <- do.call(rbind.data.frame, lat)

    coord <- cbind(lon, lat)
    colnames(coord) <- c("lon", "lat")

我正在尝试计算数据框中所有可能的行组合之间的欧几里得距离和角度。

     lon   lat       apply function on every possible combinations such as v1-v2, v1-v3, v1-v4,
v1   x1    y1        v2-v3 and so on...
v2   x2    y2         
v3   x3    y3        here are the two functions applied beetween v1 and v2 :
v4   x4    y4        **euclidian distance**    sqrt((x1-x2)^2 + (y1-y2)^2)
                     **angle**                 atan2((y1-y2),(x1-x2))*(180/pi)

如何在每种可能的行组合上应用几种功能,并在各自的列表中获取结果?我的目标是无论输入多少行,每次迭代都使用这些计算。

谢谢您的回答,如果问题看起来很傻,请多谢。我看了很多文章,但找不到我能理解和复制的解决方案。

r list function dataframe sapply
2个回答
2
投票

Base R函数combn一次生成一个矢量元素的组合m,并且可以选择将函数FUN应用于这些组合。由于输入数据是"data.frame",因此我将rownames 2乘以2。

euclidean <- function(k){ 
  f <- function(x, y) sqrt(diff(x)^2 + diff(y)^2)
  x <- unlist(coord[k[1], ])
  y <- unlist(coord[k[2], ])
  f(x, y)
}

angle <- function(k){ 
  f <- function(x, y) atan2(diff(y), diff(x))*(180/pi)
  x <- unlist(coord[k[1], ])
  y <- unlist(coord[k[2], ])
  f(x, y)
}

combn(rownames(coord), 2, euclidean)
#[1] 10515842 10515842 10515842 10515842 10515842 10515842

combn(rownames(coord), 2, angle)
#[1] 45 45 45 45 45 45

1
投票
lon <- c(505997.627175236, 505597.627175236, 515997.627175236, 505297.627175236)   
lat <- c(7941821.025438220, 7945821.025438220, 7141821.025438220, 7921821.025438220)


eDistance <- function(x1, x2, y1, y2) sqrt((x1-x2)^2 + (y1-y2)^2)

df <- data.frame(lon, lat) %>%
    mutate(joinIndex = 1:nrow(.))

df

df_combinations <- expand.grid(1:nrow(df), 1:nrow(df))

df <- df_combinations %>%
    left_join(df, by = c("Var1" = "joinIndex")) %>%
    left_join(df, by = c("Var2" = "joinIndex"))

df %>%
    mutate(distance = eDistance(lon.x, lon.y, lat.x, lat.y))
© www.soinside.com 2019 - 2024. All rights reserved.