R 获取返回列表的数据帧的两列之间的顺序匹配

R 获取返回列表的数据帧的两列之间的顺序匹配,r,R,我有一个由两个变量Var1和Var2组成的数据框。数据帧每行的两个元素已经根据先前确定的两个值之间的特征差异进行匹配。即397.1074与510.2119匹配,436.4694也与510.2119匹配 matches <- data.frame( Var1 = c(397.1074, 436.4694, 510.2119, 581.2889, 761.0372, 851.5489, 860.3277, 861.0612, 851.5489, 860.3277, 861.0612, 86

我有一个由两个变量Var1和Var2组成的数据框。数据帧每行的两个元素已经根据先前确定的两个值之间的特征差异进行匹配。即397.1074与510.2119匹配,436.4694也与510.2119匹配

matches <- data.frame(
  Var1 = c(397.1074, 436.4694, 510.2119, 581.2889, 761.0372, 851.5489, 860.3277, 861.0612, 851.5489, 860.3277, 861.0612, 860.3277, 861.0612, 861.0612,
871.4374, 861.0612, 871.4374),
  Var2=c(510.2119, 510.2119, 581.2889, 728.2789, 860.3277, 924.9473, 924.9473, 924.9473, 925.7278, 925.7278, 925.7278, 934.1579, 934.1579, 935.0957,
935.0957, 943.1851, 943.1851)
 ) 
matches
#        Var1     Var2
# 1  397.1074 510.2119
# 2  436.4694 510.2119
# 3  510.2119 581.2889
# 4  581.2889 728.2789
# 5  761.0372 860.3277
# 6  851.5489 924.9473
# 7  860.3277 924.9473
# 8  861.0612 924.9473
# 9  851.5489 925.7278
# 10 860.3277 925.7278
# 11 861.0612 925.7278
# 12 860.3277 934.1579
# 13 861.0612 934.1579
# 14 861.0612 935.0957
# 15 871.4374 935.0957
# 16 861.0612 943.1851
# 17 871.4374 943.1851
因此,结果中的第二个列表元素是:

[[2]]
[1] 436.4694 510.2119 581.2889 728.2789

[[3]] .... Etc.

列表结果将包含第1列和第2列中所有匹配的元素。即使是长度只有两个的方法。

一种可能效率不高的方法可能是:

ff = function(var2)  # a function to, recursively, match each match
{ 
   res = c(var2, matches$Var2[match(tail(var2, 1), matches$Var1)])
   if(!is.na(tail(res, 1))) res = Recall(res)
   return(c(na.omit(res)))
}

lapply(seq_len(nrow(matches)), 
       function(i) c(matches$Var1[i], ff(matches$Var2[i])))
#[[1]]
#[1] 397.1074 510.2119 581.2889 728.2789
#
#[[2]]
#[1] 436.4694 510.2119 581.2889 728.2789
#
#[[3]]
#[1] 510.2119 581.2889 728.2789
#
#[[4]]
#[1] 581.2889 728.2789
#
#[[5]]
#[1] 761.0372 860.3277 924.9473
#
#[[6]]
#[1] 851.5489 924.9473
#
#[[7]]
#[1] 860.3277 924.9473
#....

输出的长度应该是多少?17岁或更少?如果显示输出的第三个元素,可能会让事情变得更清楚。列表元素3将是[[3]]510.2119581.2889728.2789抱歉,我没有添加其余的列表元素[[4]]581.2889728.2789[[5]]761.0372860.3277924.9473[[6]]851.5489 924.9473以此类推,列表的长度将是数据帧的行数,在这种情况下17,每个列表元素的长度将取决于该行第2列中的值是否在另一行的第1列中进一步匹配。继续,直到没有匹配为止。
ff = function(var2)  # a function to, recursively, match each match
{ 
   res = c(var2, matches$Var2[match(tail(var2, 1), matches$Var1)])
   if(!is.na(tail(res, 1))) res = Recall(res)
   return(c(na.omit(res)))
}

lapply(seq_len(nrow(matches)), 
       function(i) c(matches$Var1[i], ff(matches$Var2[i])))
#[[1]]
#[1] 397.1074 510.2119 581.2889 728.2789
#
#[[2]]
#[1] 436.4694 510.2119 581.2889 728.2789
#
#[[3]]
#[1] 510.2119 581.2889 728.2789
#
#[[4]]
#[1] 581.2889 728.2789
#
#[[5]]
#[1] 761.0372 860.3277 924.9473
#
#[[6]]
#[1] 851.5489 924.9473
#
#[[7]]
#[1] 860.3277 924.9473
#....