Skip to content

Instantly share code, notes, and snippets.

@jeromyanglim jeromyanglim/charnum2num.r
Last active Aug 29, 2015

Embed
What would you like to do?
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
You can’t perform that action at this time.