R 如何将方程式应用于 4 列的每一行,其中每列都是方程式中的参数?

R How to apply an equation to each row of 4 columns where each column is a parameter in the equation?

下面是一个 3*4 矩阵,其中 2 列代表一个位置的 lat/lon 坐标,另外两列是第二个位置的坐标。我正在尝试将大圆距离公式应用于每一行。我很确定我应该在 apply 系列中使用一些东西,但不知道如何使用。

d=as.data.frame(split(as.data.frame(c( 33.43527 ,-112.01194  ,  37.72139  , -122.22111, -3.78444 , -73.30833 , -12.02667 , -77.12278,37.43555,38.88333,40.97667,28.81528)* pi/180),1:4))
colnames(d)=c('lat','lon','lat2','lon2')

这是我想应用于 3 行中每一行的方程式:

sum(acos(sin(lat) * sin(lat2) + cos(lat) * cos(lat2) * cos(lon2 -lon)) * 6371)*0.62137

lat、lon、lat2、lon2代表矩阵d中的列名。

最终的向量如下所示:

answer= 645.0978, 626.3632, 591.4725

如有任何帮助,我们将不胜感激。

我们用 [ 对 'd' 的列进行子集化(因为它是 matrix - 对于 data.frame,$ 也可以),并且然后做算术

(acos(sin(d[,"lat"]) * sin(d[,"lat2"]) + 
    cos(d[,"lat"]) * cos(d[,"lat2"]) * 
   cos(d[,"lon2"] -d[,"lon"])) * r)*0.62137
#[1]  3153.471 10892.893  6324.854

这也可以在 apply

的循环中完成
apply(d, 1, function(x) (acos(sin(x[1]) * sin(x[3]) + 
       cos(x[1]) * cos(x[3]) * cos(x[4] - x[2])) * r)* 0.62137)
#[1]  3153.471 10892.893  6324.854

您可以使用 mapply 并提供所有 4 列作为函数的参数:

一个选项是写成:

mapply(function(lat,lon,lat2,lon2)sum(acos(sin(lat) * sin(lat2) +
         cos(lat) * cos(lat2) * cos(lon2 -lon)) * 6371)*0.62137, 
       d[,"lat"],d[,"lon"],d[,"lat2"],d[,"lon2"])

#Result: With updated data
#[1] 645.0978 626.3632 591.4725

with 函数允许您使用表达式:

(acos(sin(lat) * sin(lat2) + cos(lat) * cos(lat2) * cos(lon2 -lon)) * 6371)*0.62137 

但您需要将其从 d 矩阵转换为数据帧:

 with(data.frame(d), ( acos( sin(lat) * sin(lat2) + 
                             cos(lat) * cos(lat2) * cos(lon2 -lon) ) * 6371) *
                      0.62137
     ) 
[1]  3153.471 10892.893  6324.854

不应使用 sum,因为 +sincosacos 函数都是向量化的,但 sum 函数不是。我尝试重新排列缩进,以便术语更容易识别。