Last active
August 29, 2015 14:06
-
-
Save jeromyanglim/5fb2367858ebcd6dcaf1 to your computer and use it in GitHub Desktop.
Take a data.frame x and convert all columns of class character that appear to be numeric into numeric
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
charnum2num <- function(x) { | |
# Purpose | |
# Take a data.frame x and convert all columns of class character that appear to be numeric into numeric | |
# x is a data.frame | |
# code taken from library(Hmisc) and included here to avoid the dependency | |
all.is.numeric <- function (x, what = c("test", "vector"), extras = c(".", "NA")) | |
{ | |
what <- match.arg(what) | |
old <- options(warn = -1) | |
on.exit(options(old)) | |
x <- sub("[[:space:]]+$", "", x) | |
x <- sub("^[[:space:]]+", "", x) | |
xs <- x[x %nin% c("", extras)] | |
isnum <- !any(is.na(as.numeric(xs))) | |
if (what == "test") | |
isnum | |
else if (isnum) | |
as.numeric(x) | |
else x | |
} | |
varsnumeric <- sapply(x, function(X) all.is.numeric(X, extras=c(NA, ".", "NA"))) | |
for (i in seq(varsnumeric)) { | |
if (varsnumeric[i]) { | |
x[,i] <- as.numeric(x[,i]) | |
} | |
} | |
x | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment