Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
204 views
Welcome To Ask or Share your Answers For Others

1 Answer

@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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...