Edit See this related question for some simplifications and extensions of this basic idea.
My comment on Brandon using switch :
convert.magic <- function(obj,types){ for (i in 1:length(obj)){ FUN <- switch(types[i],character = as.character, numeric = as.numeric, factor = as.factor) obj[,i] <- FUN(obj[,i]) } obj } out <- convert.magic(foo,c('character','character','numeric')) > str(out) 'data.frame': 10 obs. of 3 variables: $ x: chr "1" "2" "3" "4" ... $ y: chr "red" "red" "red" "blue" ... $ z: num 15254 15255 15256 15257 15258 ...
For really large data frames, you can use lapply instead of the for loop:
convert.magic1 <- function(obj,types){ out <- lapply(1:length(obj),FUN = function(i){FUN1 <- switch(types[i],character = as.character,numeric = as.numeric,factor = as.factor); FUN1(obj[,i])}) names(out) <- colnames(obj) as.data.frame(out,stringsAsFactors = FALSE) }
At the same time, pay attention to some of the subtleties of coercive data in R. For example, the conversion from a coefficient to a number often includes as.numeric(as.character(...)) . Also, be aware of data.frame() and as.data.frame() default behavior of converting a character to a coefficient.
joran Oct 06 2018-11-22T00: 00Z
source share