Rprogrammer
Rprogrammer

Reputation: 477

Can not convert values from factor into only numeric

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!

Upvotes: 0

Views: 39

Answers (2)

nghauran
nghauran

Reputation: 6768

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

Upvotes: 0

Andre Elrico
Andre Elrico

Reputation: 11480

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)))

Upvotes: 5

Related Questions