How can I convert certain columns only in a data frame to numeric?
For instance, I have this data frame:
structure(list(airport = c(
1) All your columns
is character
columns <- sapply(weatherDF, is.character)
airport xdate ws wd humidity
TRUE TRUE TRUE TRUE TRUE
2) Why not simply ?
weatherDF[, 3:ncol(weatherDF)] <- lapply(3:ncol(weatherDF), function(x) as.numeric(weatherDF[[x]]))
or
columns <-c("ws", "wd", "humidity")
weatherDF[, columns] <- lapply(columns, function(x) as.numeric(weatherDF[[x]]))
If your dont know which columns is numeric you can try to find it using tryCatch
like
weatherDF[,1:ncol(weatherDF)]=lapply(1:ncol(weatherDF),function(x) {
tryCatch({
as.numeric(weatherDF[[x]])
},warning = function(w) {
weatherDF[[x]]}
)} )