【问题标题】:Performing a function on all possible combinations of a subset of DF columns in R对 R 中 DF 列子集的所有可能组合执行函数
【发布时间】:2015-04-15 04:03:47
【问题描述】:

我想计算纬度/经度坐标的行对之间的距离。这可以通过 earth.dist 等各种函数轻松完成。我被困的地方是我希望这成为每晚数据质量检查过程的一部分,其中对的数量会发生变化。每行都是唯一的主题/人。有时,一些受试者可能有四组坐标,有时最大的可能是三组。有没有一种优雅的方式来执行这个计算,例如,所有可能的组合:

combn(geototal, 2])

,其中 geototal 是给定日期的坐标集数,例如x = 4 对于集合:

latitude.1, longitude.1, latitude.2, longitude.2, latitude.3, longitude.3 latitude.4, longitude.4.

我当前的循环看起来像这样,但当然错过了许多可能的组合,尤其是。当 X 大于 4 时。

x = 1; y = 2 
while(x <= geototal) 
{
  if (y > geototal) break;
  eval(parse(text = sprintf("df$distance%d_%d = earth.dist(longitude.%d,latitude.%d,longitude.%d,latitude.%d)", x, y, x, x, y, y)));
  x <- x + 1; 
  y <- y + 1;
}

感谢您对此的任何想法!

【问题讨论】:

    标签: r combn


    【解决方案1】:

    试试这样的

    # Using a built in dataset from library(fossil)
    data(fdata.lats)
    df = fdata.lats@coords
    
    # Function to do calculate pairwise distance
    foo = function(df) {
      # Find the number of pairs
      n = nrow(df)
      # Find all combination
      l = t(combn(n, 2))
      # Loop over all combination and calculate distance, store output in vector
      t = apply(l, 1, function(x) {earth.dist(df[x,])})
      # Return the list of pairs and their distance, modify here if you want to print something instead
      cbind(l, t)
    }
    
    # Test run
    foo(df)
    
                        t
     [1,]  1  2  893.4992
     [2,]  1  3  776.3101
     [3,]  1  4 1101.1145
     [4,]  1  5 1477.4800
     [5,]  1  6  444.9052
     [6,]  1  7  456.5888
     [7,]  1  8 1559.4614
     [8,]  1  9 1435.2985
     [9,]  1 10 1481.0119
    [10,]  1 11 1152.0352
    [11,]  1 12  870.4960
    [12,]  2  3  867.2648
    [13,]  2  4  777.6345
    [14,]  2  5  860.9163
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-31
      相关资源
      最近更新 更多