Jane Jane - 1 month ago 10
R Question

Initialise empty data frame of same structure as another

my R code reads data from a csv file. This data has headers and is stored in the data.frame mydata. The headers come from the csv file.

I would like to scale the data to within the [0,1] range and thus doing create another, empty, data.frame called scaled. I then loop through each column and divide by the maximum allowed value, I assume the minimum value is zero.

foreach(i = 1:ncol(mydata)) %do% {
if (i == 1){
maxval <-100 # Max depth = 100
}
else{
maxval <- max(mydata[,i],na.rm=TRUE)
}
scaled[,i] <- mydata[,i] / maxval
}


How do I create the empty scaled data.frame with the same headers and structure as mydata?

Many thanks

rbm rbm
Answer

Try following:

col1 <- 100:102
col2 <- 200:202
col3 <- 300:302

df <- cbind(col1,col2,col3)

firstrow = df[,1]/100 # first scaled by 100
scaled <- apply(df, 2, function(col) {col = col / max(col)})
scaled[,1]=firstrow

which gives

scaled

>   scaled
     col1      col2      col3
[1,] 1.00 0.9900990 0.9933775
[2,] 1.01 0.9950495 0.9966887
[3,] 1.02 1.0000000 1.0000000