2017-09-29 58 views
1

我想用BoxCoxTrans功能中的R解決偏斜的問題。如何在R中使用BoxCoxTrans函數?

但是,我有沒能得到數據幀的問題。這是我的R代碼。

df<-read.csv("dataSetNA1.csv",header=TRUE) 

dd1<-apply(df[2:61],2,BoxCoxTrans) #Except independent variable that located first column, All variables are numeric variable. 

dd1 
$LT1Y_MXOD_AMT 
Box-Cox Transformation 

96249 data points used to estimate Lambda 

Input data summary: 
    Min. 1st Qu. Median Mean 3rd Qu. Max. 
     0  0  0 19594  0 1600000 

Lambda could not be estimated; no transformation is applied 


$MOBL_PRIN 
Box-Cox Transformation 

96249 data points used to estimate Lambda 

Input data summary: 
    Min. 1st Qu. Median Mean 3rd Qu. Max. 
     0  0 100000 191229 320000 1100000 

Lambda could not be estimated; no transformation is applied 

str(dd1) 

我不知道如何獲得結果作爲數據幀。

如果我使用as.data.frame功能,此錯誤消息發佈。

dd2<-as.data.frame(dd1) 
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : 
    클래스 ""BoxCoxTrans""를 data.frame으로 강제형변환 할 수 없습니다 

請幫幫我。

回答

0

一個BoxCox轉型是在你的應變量的轉換。您可以使用MASS軟件包的Boxcox功能來找出需要進行的轉換。 Boxcox返回一個lambda值。你應該提高你的回答,比如說y,對於權力lambda,這會產生一個新的迴應變量y *。 然後就用y替換舊的數據幀的Y列*。

請注意,如果生成的lambda爲0,則應該應用對數轉換ln(y)。

1

這裏是實現你所追求的一種方式(我假設你正在改變功能):

library(caret) 
data(cars) 

#create a list with the BoxCox objects 
g <- apply(cars, 2, BoxCoxTrans) 

#use map2 from purr to apply the models to new data 

z <- purrr::map2(g, cars, function(x, y) predict(x, y)) 

#here the transformation is performed on the same data on 
#which I estimated the BoxCox lambda for 

B_trans = as.data.frame(do.call(cbind, z)) #to convert to data frame 

head(data.frame(B_trans, cars), 20) 
#outpout 

    speed  dist speed.1 dist.1 
1  4 0.8284271  4  2 
2  4 4.3245553  4  10 
3  7 2.0000000  7  4 
4  7 7.3808315  7  22 
5  8 6.0000000  8  16 
6  9 4.3245553  9  10 
7  10 6.4852814  10  18 
8  10 8.1980390  10  26 
9  10 9.6619038  10  34 
10 11 6.2462113  11  17 
11 11 8.5830052  11  28 
12 12 5.4833148  12  14 
13 12 6.9442719  12  20 
14 12 7.7979590  12  24 
15 12 8.5830052  12  28 
16 13 8.1980390  13  26 
17 13 9.6619038  13  34 
18 13 9.6619038  13  34 
19 13 11.5646600  13  46 
20 14 8.1980390  14  26 

前兩列轉換數據和第二兩個是原始數據。

另一種方式是在培訓中納入的功能轉型:

train(....preProcess = "BoxCox"...) 

更對此事:https://www.rdocumentation.org/packages/caret/versions/6.0-77/topics/train