@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)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…