Skip to content

Instantly share code, notes, and snippets.

@jeromyanglim
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeromyanglim/5fb2367858ebcd6dcaf1 to your computer and use it in GitHub Desktop.
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
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