2012-08-29 28 views
0

我有一個data.frame,我想計算相關係數使用一列對其他列(也有一些非數字列在框架中)。如何使用ddply關聯多列?

ddply(Banks,.(brand_id,standard.quarter),function(x) { cor(BLY11,x) }) 
# Error in cor(BLY11, x) : 'y' must be numeric 

我對is.numeric(x)的測試

ddply(Banks,.(brand_id,standard.quarter),function(x) { if is.numeric(x) cor(BLY11,x) else 0 }) 

但每次失敗的比較和返回0,並返回只有一列,彷彿它纔會被調用一次。傳遞給函數的是什麼?剛剛來到R,我認爲這是我失蹤的根本。

感謝

回答

4

嘗試這樣一個

cor(longley[, 1], longley[ , sapply(longley, is.numeric)]) 



    GNP.deflator  GNP Unemployed Armed.Forces Population  Year Employed 
[1,]   1 0.9915892 0.6206334 0.4647442 0.9791634 0.9911492 0.9708985 
+0

基本上和我的答案一樣,用'sed s/d/longley/ yours' ;) - 除了我現在看到,我不需要明確地轉換爲矩陣。謝謝。 –

+0

太棒了!如此接近,ddply(Banks,。(brand_id,standard.quarter),function(x){cor(x $ BLY11,x [,sapply(x,is.numeric)])}) - 讓我相關,但是我失去了專欄名稱。他們都是V1 ... V167。如何最好地獲得原始列名稱? – LCricket

+0

@LCricket將'cor(...)'包裝在'as.data.frame()'中,強制你的函數返回一個data.frame,而不是讓'plyr'將它強制爲一個。 – Justin

2

ddply分割一個data.frame成塊,和他們(小data.frames)發送到您的功能。您的x是與Banks具有相同列的data.frame。因此,is.numeric(x)FALSEis.data.frame(x)應返回TRUE

嘗試:

function(x) { 
    cor(x$BLY11, x$othercolumnname) 
} 
+0

這將爲特定的列工作,但如果我想它違背所有其他列呢?有超過100個。 – LCricket

+0

你可以把它們寫出來,或者使用'lapply(columnnames,function(n)cor(x $ BLY11,x [n]))''''''columnnames'是你想要比較的列名的向量。 – Justin

1

看起來你在做什麼,可以用sapply做,以及:

with(Banks, 
    sapply(list(brand_id,standard.quarter), function(x) cor(BLY11,x)) 
) 
+0

剛剛試過這個,並且收到了同樣的錯誤: cor(BLY11,x)中的錯誤:'y'必須是數字 – LCricket

+0

您的列是否爲數字?用'is.numeric(銀行$ brand_id)'和類似的檢查。或者更一般地說,'sapply(名字(銀行),函數(x)類(Banks [,x,drop = TRUE]))' –

1

此功能在一大塊工作:

calc_cor_only_numeric = function(chunk) { 
    is_numeric = sapply(chunk, is.numeric) 
    return(cor(chunk[-is_numeric])) 
} 

並且可以使用ddply

ddply(banks, .(cat1, cat2), calc_cor_only_numeric) 

我無法檢查代碼,但這應該讓你開始。

4

從心病:

If ‘x’ and ‘y’ are matrices then the covariances (or correlations) between the columns of ‘x’ and the columns of ‘y’ are computed.

所以你唯一的真正的工作是消除非數字列:

# An example data.frame containing a non-numeric column 
d <- cbind(fac=c("A","B"), mtcars) 

## Calculate correlations between the mpg column and all numeric columns 
cor(d$mpg, as.matrix(d[sapply(d, is.numeric)])) 
    mpg  cyl  disp   hp  drat   wt  qsec 
[1,] 1 -0.852162 -0.8475514 -0.7761684 0.6811719 -0.8676594 0.418684 
      vs  am  gear  carb 
[1,] 0.6640389 0.5998324 0.4802848 -0.5509251 

編輯:而事實上,作爲@ MYaseen208的回答顯示,不需要將數據幀顯式轉換爲矩陣。以下兩個工作就好了:

cor(d$mpg, d[sapply(d, is.numeric)]) 

cor(mtcars, mtcars)