簡體   English   中英

匯總列

[英]Aggregating columns

我有n列和r行的數據框。 我想確定哪一列與第1列最相關,然后合計這兩列。 聚合列將被視為新列1。然后,從集合中刪除最相關的列。 因此,日期的大小將減少一列。 然后,我重復該過程,直到數據幀result具有n列,第二列是兩列的聚合,第三列是三列的聚合,以此類推。因此,我想知道是否有效率更高或更快速的方法獲得我想要的結果的方法。 我已經嘗試過各種方法,但到目前為止還沒有成功。 有什么建議么?

n <- 5
r <- 6


> df
    X1   X2   X3   X4   X5
1 0.32 0.88 0.12 0.91 0.18
2 0.52 0.61 0.44 0.19 0.65
3 0.84 0.71 0.50 0.67 0.36
4 0.12 0.30 0.72 0.40 0.05
5 0.40 0.62 0.48 0.39 0.95
6 0.55 0.28 0.33 0.81 0.60

result如下所示:

> result
    X1   X2   X3   X4   X5
1 0.32 0.50 1.38 2.29 2.41
2 0.52 1.17 1.78 1.97 2.41
3 0.84 1.20 1.91 2.58 3.08
4 0.12 0.17 0.47 0.87 1.59
5 0.40 1.35 1.97 2.36 2.84
6 0.55 1.15 1.43 2.24 2.57

我認為大多數緩慢和最終崩潰都是由於循環期間的內存開銷而不是相關性造成的(盡管也可以像@coffeeinjunky所說的那樣進行改善)。 這很可能是由於R中修改了data.frames的結果。考慮切換到data.tables並利用它們的“按引用分配”范式。 例如,下面是將您的代碼轉換為data.table語法的代碼。 您可以為兩個循環計時,比較性能並注釋結果。 干杯。

n <- 5L
r <- 6L

result <- setDT(data.frame(matrix(NA,nrow=r,ncol=n)))
temp <- copy(df) # Create a temporary data frame in which I calculate the correlations
set(result, j=1L, value=temp[[1]]) # The first column is the same

for (icol in as.integer(2:n)) {
  mch <- match(c(max(cor(temp)[-1,1])),cor(temp)[,1]) # Determine which are correlated most
  set(x=result, i=NULL, j=as.integer(icol), value=(temp[[1]] + temp[[mch]]))# Aggregate and place result in results datatable
  set(x=temp, i=NULL, j=1L, value=result[[icol]])# Set result as new 1st column
  set(x=temp, i=NULL, j=as.integer(mch), value=NULL) # Remove column
}

嘗試

for (i in 2:n) {
  maxcor <- names(which.max(sapply(temp[,-1, drop=F], function(x) cor(temp[, 1], x) )))
  result[,i] <- temp[,1] + temp[,maxcor] 
  temp[,1] <- result[,i] # Set result as new 1st column
  temp[,maxcor] <- NULL # Remove column
}

造成此錯誤的原因是,在最后一次迭代中,子集temp產生單個向量,並且在這種情況下標准R行為是將類從數據幀減少到向量,這導致sapply僅傳遞第一個元素, sapply

還有一條評論:當前,您使用的是最正的相關性,而不是最強的相關性,也可能是負相關性。 確保這是您想要的。


要在評論中解決您的問題:請注意,可以通過避免重復計算來改進您的舊代碼。 例如,

   mch <- match(c(max(cor(temp)[-1,1])),cor(temp)[,1])

兩次包含命令cor(temp) 這意味着每個相關都被計算兩次。 替換為

  cortemp <- cor(temp)
  mch <- match(c(max(cortemp[-1,1])),cortemp[,1])

應該將初始代碼行的計算負擔減少一半。

暫無
暫無

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

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