title: min max scaling/normalization in r for train and test data
body: <p>I am looking to create a function that takes in the training set and the testing set as its arguments, min-max scales/normalizes and returns the training set and uses those <strong>same</strong> values of minimum and range to min-max scale/normalize and return the test set.</p>
  
  <p>So far this is the function I have come up with:</p>
  
  <pre><code>min_max_scaling &lt;- function(train, test){
  
    min_vals &lt;- sapply(train, min)
    range1 &lt;- sapply(train, function(x) diff(range(x)))
  
    # scale the training data
  
    train_scaled &lt;- data.frame(matrix(nrow = nrow(train), ncol = ncol(train)))
  
    for(i in seq_len(ncol(train))){
      column &lt;- (train[,i] - min_vals[i])/range1[i]
      train_scaled[i] &lt;- column
    }
  
    colnames(train_scaled) &lt;- colnames(train)
  
    # scale the testing data using the min and range of the train data
  
    test_scaled &lt;- data.frame(matrix(nrow = nrow(test), ncol = ncol(test)))
  
    for(i in seq_len(ncol(test))){
      column &lt;- (test[,i] - min_vals[i])/range1[i]
      test_scaled[i] &lt;- column
    }
  
    colnames(test_scaled) &lt;- colnames(test)
  
    return(list(train = train_scaled, test = test_scaled))
  }
  </code></pre>
  
  <p>The definition of min max scaling is similar to this question asked earlier on SO - <a href="https://stackoverflow.com/questions/12969623/normalisation-of-a-two-column-data-using-min-and-max-values">Normalisation of a two column data using min and max values</a></p>
  
  <p>My questions are:<br>
   1. Is there a way to vectorize the two <code>for</code> loops in the function? e.g. using <code>sapply()</code><br>
   2. Are there any packages that allow us to do what we are looking to do here?</p>