簡體   English   中英

合並多個數據幀的所有可能組合

[英]Merge all possible combinations of multiple data frames

我想按列合並這三個數據幀的所有可能的對組合(即九個組合)

frame1 = data.frame(a=c(1,2,3), b=c(1,2,3), c=c(1,2,3))
frame2 = data.frame(a=c(2,1,3), b=c(2,1,3), c=c(2,1,3))
frame3 = data.frame(a=c(3,2,1), b=c(3,2,1), c=c(3,2,1))

它們每個都包含相同的3行,但順序不相同,因此我也希望合並是通過合並兩個文件中的列a和b的一對值的巧合來實現的。 例:

a b c
1 1 1 
2 2 2
3 3 3

+

a b c
2 2 2
1 1 1   
3 3 3

=

a.x b.x c.x a.y b.y c.y
1 1 1 1 1 1  
2 2 2 2 2 2
3 3 3 3 3 3

然后,我想獲取每個合並文件中存在的列cx和cy的每對值之間的絕對值之差,並將所有這些差值求和,從而獲得一個“分數”(當然在此示例中為零) ,我想將其添加到對應單元格中的空矩陣3x3中(即frame1 vs.frame 2的得分應位於單元格[2,1]中,等等):

nframes = 3
frames = c(frame1,frame2,frame3)

matrix = matrix(, nrow = nframes, ncol = nframes)
matrix_scores = data.frame(matrix)

for (i in frames){
  for (j in frames)
   {
    x = merge(i, j, by=c("a","b"))
    score = sum(abs(x$c.x - x$c.y))
    matrix_scores[j,i] <- score
  }
}

但是,當我運行循環時,會收到以下消息:

Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns

另外,我了解到

matrix_scores[j,i] <- score

也會產生一個錯誤,但是對於循環的第一次迭代(frame1 vs. frame1),我不知道如何表達我想要將分數存儲在單元格[1,1]中。

生成的矩陣應為3x3矩陣,其中包含全零:

       f1 f2 f3
frame1 0 0 0
frame2 0 0 0
frame3 0 0 0

你可以做:

# Put all frames in a list
d <- list(frame1, frame2, frame3)
# get all merge-combinations
gr <- expand.grid(1:length(d), 1:length(d))

# function to merge and get the sum diff:
foo <- function(i, x, gr){
  tmp <- merge(x[[gr[i, 1]]], x[[gr[i, 2]]], by=c("a", "b"))
  sum(abs(tmp$c.x - tmp$c.y))
}

# result matrix
matrix(sapply(1:nrow(gr), foo, d, gr), length(d), length(d),  byrow = T)
      [,1] [,2] [,3]
[1,]    0    0    0
[2,]    0    0    0
[3,]    0    0    0

# The scores are set as followed:
matrix(apply(gr, 1, paste, collapse="_"), 3, 3,  byrow = T)
      [,1]  [,2]  [,3] 
[1,] "1_1" "2_1" "3_1"
[2,] "1_2" "2_2" "3_2"
[3,] "1_3" "2_3" "3_3"


# alternative using apply:

# function to merge and get the sum diff:
foo <- function(y, x){
  tmp <- merge(x[[ y[1] ]], x[[ y[2] ]], by=c("a", "b"))
  sum(abs(tmp$c.x - tmp$c.y))
}
# result matrix
matrix(apply(gr, 1, foo, d), length(d), length(d),  byrow = T)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM