How to change the class of a variable within a table/ data frame/ Tibble?

Asked

Viewed 3,371 times

2

I have a table called tab01 with the following variables (columns) and their respective classes in parentheses: uf (Character), regiao (Character), ano (double) and pop (double).

I want, inside the table:
1) transform the variable region to the factor class, and
2) inform R that the variable year corresponds to a "date"

So how do I do this using the R base? And using the tidyverse ecosystem?

1 answer

4


first would be nice if you exposed your data or a part of it to make the problem playable. But, here taking a generic case.

library(dplyr)

tibble(uf=c("AM", "RJ", "SC"),
       regiao=c("norte", "sudeste", "sul"),
       ano=c(1989, 1987, 1986),
       pop=runif(3)) %>% 
       print() %>% 
       {.} -> dt

#     uf  regiao   ano        pop
#  <chr>   <chr> <dbl>      <dbl>
#1    AM   norte  1989 0.05092618
#2    RJ sudeste  1987 0.54035176
#3    SC     sul  1986 0.54615493

To change the typing of variables just apply the function mutate package dplyr. In part of the date one must establish a day and a month to use the type date, in the example below I used the first day of January, which will be applied to all lines.

dt %>% 
        mutate(regiao=as.factor(regiao)) %>% 
        mutate(ano=as.Date(ISOdate(ano, 1, 1)))

#     uf  regiao        ano        pop
#  <chr>  <fctr>     <date>      <dbl>
#1    AM   norte 1989-01-01 0.05092618
#2    RJ sudeste 1987-01-01 0.54035176
#3    SC     sul 1986-01-01 0.54615493

What you could do differently here would be to use a single mutate to change both columns, such as:

dt %>% 
        mutate(regiao=as.factor(regiao),
               ano=as.Date(ISOdate(ano, 1, 1)))
  • Thank you, Rafael, thank you! To complement, from your answer I realized that to do the same thing without using the pipe, just put dt inside the mutate: mutate(dt, regiao = as.factor(regiao), year = as.Date(Isodate(year, 1, 1)))

  • @Enoch, bear in mind that dt %>% mutate(...) is equivalent to mutate(dt, ...)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.