简体   繁体   中英

Function for normalizing one data frame to be applied on a second data frame in R

This is home work.

I am new to R.

I have two data frames each containing two columns of data. I have to find a function that normalize the first data frame to a mean of 0 and a variance of 1 - for both columns. Then I want to apply that function on the second data frame.

I have tried this:

my_scale_test <- function(x,y) {
    apply(y, 2, function(x,y) {
        (y - mean(x ))/sd(x)
    }) 
}

where x is the first data frame and y is the data frame to be normalized.

Can some one help me?

Edit:

I have now tried this aswell, but not working either:

scale_func <- function(x,y) {
    xmean <- mean(x)
    xstd <- sd(x)
    yout <- y
    for (i in 1:length(x[1,]))
        yout[,i] <- yout[,i] - xmean[i]
    for (i in 1:length(x[1,]))
        yout[,i] <- yout[,i]/xsd[i]
invisible(yout)
}

Edit 2: I found this working function for MatLab (which i tried to translate in edit 1):

function [ Xout ] = scale( Xbase, Xin )
    Xmean = mean(Xbase);
    Xstd = std(Xbase);
    Xout = Xin;
    for i=1:length(Xbase(1,:))
        Xout(:,i) = Xout(:,i) - Xmean(i);
    end

    for i=1:length(Xbase(1,:))
        Xout(:,i) = Xout(:,i)/Xstd(i);
    end
end

Can someone help me translate it?

Since you are new to R, let's try something really basic.

my_scale_test <- function(x, y) {
  y.nrow <- nrow(y)
  x.mean <- data.frame(t(apply(x, 2, mean)))
  x.sd <- data.frame(t(apply(x, 2, sd)))
  # To let x.mean and x.sd have the same dimension as y, let's repeat the rows. 
  x.mean <- x.mean[rep(1, y.nrow), ]
  x.sd <- x.sd[rep(1, y.nrow), ]
  (y - x.mean)/x.sd
}

To test, try

set.seed(1)
x <- data.frame(matrix(rnorm(10), nrow = 5))
y <- x
result <- my_scale_test(x, y)
apply(result, 2, mean)
apply(result, 2, sd)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM