How to change the name of a column

5

I have a date.frame, I changed the data class of the date column, and then I separated the other three column through the Separate command whose names were% Y,% me% d, I would like to change these names to year, month it is day. However, when trying to rename the columns, using the Rename command gives an error.

> as.data <- as.Date(dados$data)

> meus.dados <- separate(data = dados, col = data, into = c("%Y", "%m","%d"), sep = "-")

> meus.dados[1:5, 1:9]

Source: local data frame [5 x 9]

   posicao    %Y    %m    %d              especie    BF   CA2    CB    CP
     (chr) (chr) (chr) (chr)                (chr) (dbl) (dbl) (dbl) (dbl)
1  direita  2012    05    22     Canis familiaris     0     0     0     0
2  direita  2012    05    22     Canis familiaris     0     0     0     0
3 esquerda  2012    05    24 Dasypus novemcinctus     0     0     0     1
4 esquerda  2012    05    25     Canis familiaris     1     0     0     0
5 esquerda  2012    05    26 Dasypus novemcinctus     0     0     0     1

> rename(meus.dados, ano=" %Y", mes="%m", dia="%d")
 Error: Arguments to rename must be unquoted variable names. Arguments ano, mes, dia are not.

I do not know what to do !!

    
asked by anonymous 05.05.2016 / 03:32

2 answers

4

You can use the names function to get, and also to change the name of the columns. In your case, you can use names(meus.dados)[2:4] <- c("ano", "mes", "dia") . The full example below shows it being used:

meus.dados <- data.frame(
    posicao = c("direita", "direita", "esquerda", "esquerda"),
    YY = c("2012", "2012", "2012", "2012"),
    MM = rep("05", 4),
    DD = c("22", "22", "24", "25"),
    especie = c("cf", "cf", "dn", "cf")
)

names(meus.dados)[2:4] <- c("ano", "mes", "dia")

meus.dados
    
05.05.2016 / 06:16
2

Because variable names have non-R recognized char- acters, you need to use the ' character wrapped in their name. Then it would be necessary to do so:

meus.dados <- data_frame(
  posicao = c("direita", "direita", "esquerda", "esquerda"),
  "%Y" = c("2012", "2012", "2012", "2012"),
  "%m" = rep("05", 4),
  "%d" = c("22", "22", "24", "25"),
  especie = c("cf", "cf", "dn", "cf")
)

rename(meus.dados, ano = '%Y', mes = '%m', dia = '%d')

But as @molx said in the comment you could already put those names directly by the function separate .

    
05.05.2016 / 15:33