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
@Enoch, bear in mind that
dt %>% mutate(...)
is equivalent tomutate(dt, ...)
– Guilherme Marthe