0

I want to convert this variable into numeric, as you can see:

> class(DATA$estimate)
[1] "factor"
> head(DATA$estimate)
[1] 0,253001909 0,006235543 0,005285019 0,009080499 6,580140903 0,603060006
57 Levels: 0,000263863 0,000634365 0,004405696 0,005285019 0,006235543 0,009080499 0,009700147 0,018568434 0,253001909 ... 7,790580873
> 

But when I want to convert, look what I have got

> DATA$estimate<-as.numeric(DATA$estimate)
> DATA$estimate
 [1]  9  5  4  6 51 12  3 53 11  8  1  7 15 27 30 29 28 31 21 23 22 39 38 37 33 26 34 52 57 50 24 18 20 10  2 55 54 56 36 32 35 44 46
[44] 48 19 25 16 43 41 40 49 42 47 14 17 13 45

It's not numeric and I don't understand how the program gives these numbers!

10
  • This R joy. Try as.numeric(as.character(data$estimate)) Commented Jun 20, 2018 at 7:38
  • 2
    This is a common mistake that people make in R. You have to use as.numeric(levels(DATA$estimate))[DATA$estimate] Commented Jun 20, 2018 at 7:40
  • 2
    Possible duplicate of How to convert a factor to integer\numeric without loss of information? Commented Jun 20, 2018 at 7:40
  • 2
    @ANG you changed the OP input data. He does not have "." but ",". Commented Jun 20, 2018 at 7:47
  • 1
    @ANG both we refer to R inferno/ CHIMERAS and we were correct, but we forgot about ",". Commented Jun 20, 2018 at 7:48

2 Answers 2

5

data:

fac <- factor(c("0,253001909" ,"0,006235543" ,"0,005285019" ,"0,009080499" ,"6,580140903" ,"0,603060006"))

I convert to character, then turn the "," into ".", then convert to numeric.

as.numeric(sub(",",".",as.character(fac)))

in your case its:

DATA$estimate<-as.numeric(sub(",",".",as.character(DATA$estimate)))
Sign up to request clarification or add additional context in comments.

Comments

0

You can also scan() your factor variable and specify , as decimal separator

fac <- factor(c("0,253001909" ,"0,006235543" ,"0,005285019" ,"0,009080499" ,
                "6,580140903" ,"0,603060006"))
scan(text = as.character(fac), dec = ",")
#output
[1] 0.253001909 0.006235543 0.005285019 0.009080499 6.580140903
[6] 0.603060006

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.