R - convert chr value to num from multiple columns?

Viewed 826

I have this data frame and I want to change the chr values to num:

> dput(Df)
structure(list(`@MeasurementDateGMT` = c("2016-09-01 00:00:00", 
"2016-09-01 01:00:00", "2016-09-01 02:00:00", "2016-09-01 03:00:00", 
"2016-09-01 04:00:00", "2016-09-01 05:00:00", "2016-09-01 06:00:00", 
"2016-09-01 07:00:00", "2016-09-01 08:00:00", "2016-09-01 09:00:00", 
"2016-09-01 10:00:00", "2016-09-01 11:00:00", "2016-09-01 12:00:00", 
"2016-09-01 13:00:00", "2016-09-01 14:00:00", "2016-09-01 15:00:00", 
"2016-09-01 16:00:00", "2016-09-01 17:00:00", "2016-09-01 18:00:00", 
"2016-09-01 19:00:00", "2016-09-01 20:00:00", "2016-09-01 21:00:00", 
"2016-09-01 22:00:00", "2016-09-01 23:00:00"), `@Value` = c("10.9", 
"9.8", "9.9", "14.1", "13.6", "16.5", "15", "18.5", "18", "17", 
"16.6", "12", "12.1", "18.1", "15.9", "15.9", "16.9", "21.6", 
"23.5", "40.7", "16.6", "12.7", "12.4", "12.2")), .Names = c("@MeasurementDateGMT", 
"@Value"), class = "data.frame", row.names = c(NA, 24L))

Code to convert:

columns <- sapply(Df, is.factor)
Df[, columns] <- lapply(Df[, columns, drop = FALSE], function(x) as.numeric(as.character(x)))

Result:

> str(Df)
'data.frame':   24 obs. of  2 variables:
 $ @MeasurementDateGMT: chr  "2016-09-01 00:00:00" "2016-09-01 01:00:00" "2016-09-01 02:00:00" "2016-09-01 03:00:00" ...
 $ @Value             : chr  "10.9" "9.8" "9.9" "14.1" ...

They are still chr. What have I missed? any ideas?

2 Answers
Related