Take the 2-minute tour ×

Suppose I have a data.frame that's completely numeric. If I make one entry of the first column a character (for example), then the entire first column will become character.

Question: How do I reverse this. That is, how do I make it such that any character objects inside the data.frame that are "obviously" numeric objects are forced to be numeric?


test <- data.frame(matrix(rnorm(50),10))
test[1,1] <- "TEST"

So my goal here would be to go FROM the way that test is now, TO a state of affairs where test[2:10] is numeric. So I guess I'm asking for a function that does this over an entire data.frame.

share|improve this question
A column in an R dataframe can only have one type, so if you put a string in like "TEST" it's forced to change that entire column to a string. You can do test$X1 <- as.numeric(test$X1), but note that since "TEST" is not "obviously numeric" it will be converted to NA. Otherwise, you could make sure things were numeric before assigning them to the data frame: test[1, 1] <- as.numeric("TEST") –  mathematical.coffee Dec 3 '12 at 5:41

2 Answers 2

up vote 4 down vote accepted

Short answer is you cannot.
As was mentioned in the comments, in a data frame, all elements of a column must have the same mode.

If you would like to specifically find the values that are "number like" you can use the following (where vec here would be, say, a data frame column)


You can then convert these, but unfortunately you cannot put the converted values back into the same column. As as you do, they will be coerced back to character

As for a function that can convert the whole dataframe to numeric (realizing that isolating specific entries as exceptions is not possible), you can use sapply

  sapply(dataFrameName, as.numeric)
share|improve this answer
Or we could use data.matrix(...) –  Jase Dec 3 '12 at 6:18
Sure, but if you have columns that look like numbers but are in fact factors, data.matrix might give unexpected results –  Ricardo Saporta Dec 3 '12 at 6:41

You are allowed to have vectors of type list in a data.frame, and the list can contain any type of object except functions as long as it is of the same length as the other columns in the data.frame, e.g.:

mydataframe <- data.frame(numbers=1:3)
mydataframe$mylist <- list(1, 'plum', 5)
#  numbers mylist
#1       1      1
#2       2   plum
#3       3      5
sapply(mydataframe, typeof)
#  numbers    mylist 
#"integer"    "list" 
sapply(mydataframe$mylist, typeof)
#[1] "double"    "character" "double"  
share|improve this answer

Your Answer


