2016-02-29 82 views
0

我有300行和70列的數據幀測試樣本。 如何將整個數據幀轉換爲標準的標準格式。將整個數據幀轉換爲標準標準格式R

我寫下述R代碼片斷:

normalization<- function(testsample){ 
newSample<-data.frame(1:nrow(testSample)) 
for(j in 1:ncol(testsample)){ 
    mu<-mean(testsample[,j]) 
    sigma<-sd(testsample[,j]) 
    colName<- names(testsample) 
     for(i in 1:nrow(testsample)){ 
     newSample$colName[j] <- transmute(testsample,colName[j]=((testsample[i,j]-mu)/sigma)   

    } 
    } 

print(newSample) 
return(newSample) 
} 
z<-normalization(testsample) 
在其中,i用於蛻變功能我得到了誤差COLNAME [j]的行

。 我明白錯誤。我正試圖同時評估LHS和RHS,這是不可能的,它只是取代了這些值。

不使用任何r軟件包如何解決並將整個數據幀轉換爲標準正常形式。

+0

如何使用功能'scale'? – 2016-02-29 08:03:44

+0

@ David,對於數據框中的某些列,它返回NA值。你可以解釋一下嗎? – azad

回答

-1

我認爲以下行應當工作:

newSample <- testSample 
for(j in 1:ncol(testsample)){ 
    mu <- mean(testsample[,j]) 
    sigma <- sd(testsample[,j]) 
    newSample[,j] <- (newSample[,j]-mu)/sigma) 
} 

否則儘量內transmute刪除索引i

我沒有scale的經驗,但這可能是一個更好,更簡單的想法。

0

正如我在評論說,用scale功能:

x <- matrix(runif(300*70), 300, 70) 
x <- as.data.frame(x) 
dim(x) 
# [1] 300 70 

y <- scale(x) 

head(apply(y, 2, mean)) 
#   V1   V2   V3   V4   V5   V6 
# -6.641678e-17 5.092425e-17 -4.435159e-17 8.974583e-17 8.300724e-17 9.999023e-17 

head(apply(y, 2, sd)) 
# V1 V2 V3 V4 V5 V6 
# 1 1 1 1 1 1