Transform factor into numerical R

2

Good evening!

I'm doing a job where I import a base and after importing I create a range of values.

Ex. I import the base with read.csv

dados <- read.csv(base, header=TRUE, sep=',')

But in this column of values ($$), which I will use to create the track, when importing changes to factor . Therefore I use the following code for transformation.

dados$valores <- is.numeric(dados$valores)

What happens here is that the values in the column change all.

Ex in column value 100, it turns 2600. could anyone help me?

    
asked by anonymous 05.06.2018 / 04:45

3 answers

3

This problem is quite common when working with objects of class data.frame , which is the class of objects that the read.table and derived functions produce.

To avoid this, just see that by default the value of argument stringsAsFactors is TRUE . See help("read.csv") , for example.

Note that read.csv only reads numbers as factor if those numbers have non-numeric characters. There must be something in the file that forces R to interpret the values as strings. (alphanumeric?)

The solution to not creating a column of class factor should be

dados <- read.csv(base, stringsAsFactors = FALSE)

There are two other ways to transform objects from class read.csv to read.table .

dados$valores <- as.numeric(as.character(dados$valores))
dados$valores <- as.numeric(levels(dados$valores))[dados$valores]

From the help page header = TRUE , section sep = "," :

  

To transform a factor f to approximately its original numeric values,   as.numeric (levels (f)) [f] is recommended and slightly more efficient   than as.numeric (as.character (f)).

    
05.06.2018 / 11:35
0

Ronaldo, all right?

Setting the stringsAsFactors = FALSE parameter prevents character fields from being converted to factor.

Example:

df <- read.csv("dados.csv", stringsAsFactors = FALSE)
    
05.06.2018 / 22:22
-2
dados <- read.csv(base, stringsAsFactors = FALSE)

Modify the function read.csv2

dados <- read.csv2(base, stringsAsFactors = FALSE)
    
08.10.2018 / 20:46