r - Mutate all columns applying type conversion -


i have dataframe , convert column types. actualy have function :

library(dplyr)  convertdftypes <- function(obj, types) {    (i in 1:length(obj)){      fun <- switch(types[i], character = as.character,                    numeric = as.numeric,                    factor = as.factor,                    integer = as.integer,                    posixct = as.posixct,                    datetime = as.posixct)      name <- names(obj)[i]      expr <- paste0("obj %<>% mutate(", name, " = fun(", name, "))")      eval(parse(text = expr))   }    return(obj) }  mydf <- data_frame(date = seq(sys.date() - 4, sys.date(), = 1),                     x = 1:5,                    y = 6:10)  coltypes <- c("character", "character", "integer")  str(mydf)  # classes ‘tbl_df’, ‘tbl’ , 'data.frame':  5 obs. of  3 variables: #   $ date: date, format: "2015-05-11" "2015-05-12" ... # $ x   : int  1 2 3 4 5 # $ y   : int  6 7 8 9 10  mydf %>%    convertdftypes(coltypes) %>%    str  # classes ‘tbl_df’, ‘tbl’ , 'data.frame':  5 obs. of  3 variables: #   $ date: chr  "2015-05-11" "2015-05-12" "2015-05-13" "2015-05-14" ... # $ x   : chr  "1" "2" "3" "4" ... # $ y   : int  6 7 8 9 10 

(in first time used obj[,i] <- fun(obj[,i]) unlikely work objects of class tbl)

it works fine if it's slow complex types conversion (e.g. date/datetime) on "larges" dataframes. don't know if using eval(parse great idea column replacement , think function can improved without using for loop.

is there way apply different function each column, mutate_each using different function each column , not same all.

do have ideas improve function ?

thank

here more general way achieve goal of transforming column types:

suppose want transform int columns numeric, can using 1 pipe:

mydf %>%  mutate_each_( funs(as.numeric(.)), names( .[,sapply(., is.integer)] )) 

Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -