2016-02-29 86 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