Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

r - Transforming all numerical variables in a dataframe with a function

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...