Data conversion factor for numeric

3

In the following example:

> str(rhm)
'data.frame':   24 obs. of  4 variables:
 $ plant     : Factor w/ 1 level "LaR": 1 1 1 1 1 1 1 1 1 1 ...
 $ time      : int  0 0 0 0 3 3 3 3 7 7 ...
 $ Tratamento: Factor w/ 4 levels "T1pH1","T1pH2",..: 1 2 3 4 1 2 3 4 1 2 ...
 $ wt        : Factor w/ 20 levels "0,0013","0,0017",..: 20 20 20 20 10 16 18 17 12 19 ...
> str(unclass(rhm$wt))
 atomic [1:24] 20 20 20 20 10 16 18 17 12 19 ...
 - attr(*, "levels")= chr [1:20] "0,0013" "0,0017" "0,0036" "0,0045" ...

When attempting to transform the variable wt into number, instead of "0.0013", "0.0017" ... appear:

as.numeric(rhm$wt)
[1:24] 20 20 20 20 10 16 18 17 12 19 ...

How to convert wt to numbers?

I tried two suggested ways in the forum:

as.numeric(as.character(rhm$wt))
as.numeric(levels(rhm$wt))[rhm$wt]

However, my data is replaced by NAs:

[1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
Warning message:
NAs introduced by coercion 

How can I transform my data correctly?

    
asked by anonymous 19.07.2016 / 20:23

1 answer

2

In% of%, the decimal placeholder is R . For your code to work you have two options:

Use the following code to convert . to numeric:

as.numeric(gsub(",", ".", as.character(rhm$wt)))

The factor function with these arguments changes all the commas by point. Then R can convert from gsub to chr . Here's a simple example:

> as.numeric("0,1")
[1] NA
Warning message:
NAs introduced by coercion 
> as.numeric(gsub(",", ".", "0,1"))
[1] 0.1

Another way is: when reading data, you're probably using numeric . Use the argument read.table indicating that your decimal placeholder is sep = "," .

    
19.07.2016 / 20:39