-1

I need to apply transformations to all numeric variables of a large dataframe. The dataframe has variables of other types as well. My initial idea was to iterate over all the columns, check if they are numerical and then divide them by 1000.

I've got stuck in my code for a function, would appreciate some pointers here:

transformDivideThousand <- function(data_frame){
    for(i in ncol(data_frame)){
        if (is.numeric(data_frame[i])) {
            data_frame[i]/1000
        }
    }
    return(data_frame)
}

The execution of the function:

test <- transformDivideThousand(mypatients)
  • test is a dataframe, but the transformations are not happening. Where did I err?
  • As an extra, I would also like transformDivideThousand to have an optional argument where I could pass a list with the names for the variables to use, if empty, than iterate over all of them.
lf_araujo
  • 1,991
  • 2
  • 16
  • 39
  • 5
    You have to assign the result back in the loop. `data_frame[[i]]<-data_frame[[i]]/1000`. Use the double square brackets to extract a column; you should learn the difference between `[` and `[[`. For instance, `is.numeric(data_frame[i])` is not going to return `TRUE` pretty much ever. Also, the loop is not properly defined; should be `for(i in 1:ncol(data_frame))`, otherwise only the last column is considered. – nicola Apr 28 '16 at 05:40

1 Answers1

4

@nicola's comment explains what's going wrong with your loop. Another option is to use sapply to identify the numeric columns, which results in more succinct code. For example, using the built-in iris data frame:

iris[, sapply(iris, is.numeric)] = 
        iris[, sapply(iris, is.numeric)]/1000

You can just run this directly on a data frame, as above, or put it inside a function:

tDT <- function(data_frame) {

  data_frame[, sapply(data_frame, is.numeric)] = 
    data_frame[, sapply(data_frame, is.numeric)]/1000

  return(data_frame)

}

Then, to run it:

iris.new = tDT(iris)

For future reference, per @nicola's comment, here's how to make the for loop version work:

tDT2 <- function(data_frame) {

  for (i in 1:ncol(data_frame)) {
    if (is.numeric(data_frame[,i])) {
      data_frame[,i] = data_frame[,i]/1000
    }
  }
  return(data_frame)
}
eipi10
  • 91,525
  • 24
  • 209
  • 285