CodingButStillAlive CodingButStillAlive - 10 months ago 54
R Question

In R: Type conversion of data frames with mixed data types

I generally like R, but the type conversion issues are driving me crazy.

Following issue:

I read a data frame from a database connection. The result is a data frame with character columns.

I know that the first column is a date format - all the others are numeric. However, no matter how I tried to convert the character columns of the data frame into the correct types, it didn't work out.

Upon conversion of the data frame into a matrix and then back into a data frame, all columns became type factor - and casting factors into numerics created wrong results cause the indices of the factor levels were converted instead of the real values.

Moreover, if the table is big in size - I do not want to convert each column manually. Isn't there a way to get this done automatically?


We can use type.convert by looping over the columns of the dataset with lapply. Convert the columns to character and apply the type.convert. If it is is a character class, it will convert to factor which we can reconvert it to Date class (as there is only a single column with character class. It is not sure about the format of the 'Date' class, so in case it is a different format, specify the format argument in as.Date).

df1[] <- lapply(df1, function(x) {x1 <- type.convert(as.character(x))
                             as.Date(x1) else x1})