-1

I am trying to do something with [R] which should be extremely simple: convert values in a data.frame to numbers, as I need to test for their values and r does not recognize them as number.

When I convert a decimal number to numeric, I get the correct value:

> a <- as.numeric(1.2)
> a
[1] 1.2

However, when I extract a positive value from the data.frame then use as.numeric, the number is rounded up:

> class(slices2drop)
[1] "data.frame"
> slices2drop[2,1]
[1] 1.2
Levels: 1 1.2
> a <- as.numeric(slices2drop[2,1])
> a
[1] 2

Just in case:

> a*100
[1] 200

So this is not a problem with display, the data itself is not properly handled.

Also, when the number is negative, I get NA:

> slices2drop[2,1] <- -1
> a <- as.numeric(slices2drop[2,1])
> a
[1] NA

Any idea as to what may be happening?

3
  • 1
    Note that the first time you show us slices2drop[2,1] it returns a factor. That is your issue - you're working with a factor - not numeric data. Commented Nov 18, 2013 at 20:12
  • 1
    See ?factor, Warning section. Commented Nov 18, 2013 at 20:14
  • 1
    Please take a look at this question: stackoverflow.com/questions/3418128/… Commented Nov 18, 2013 at 20:14

2 Answers 2

11

This problem has to do with factors. To solve your problem, first coerce your factor variable to be character and then apply as.numeric to get what you want.

> x <- factor(c(1, 1.2, 1.3)) # a factor variable
> as.numeric(x)  
[1] 1 2 3

Integers number are returned, one per each level, there are 3 levels: 1, 1.2 and 1.3, therefore 1,2,3 is returned.

> as.numeric(as.character(x)) # this is what you're looking for
[1] 1.0 1.2 1.3

Actually as.numeric is not rounding your numbers, it returns a unique integer per each level in your factor variable.

Sign up to request clarification or add additional context in comments.

Comments

1

I faced a similar situation where the conversion of factor into numeric would generate incorrect results.

When you type: ?factor

The Warning mentioned with the factor variables explains this complexity very well and provides the solution to this problem as well. It's a good place to start working with...

Another thing to consider is that, such conversion would transform NULLs into NAs

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.