0

I have a dataframe named "Num_casos_Sar" with a structure like that:

  Cod_municip  Ano Not_Sarampo
1      310110 1989           3
2      310160 1988           0
3      310350 1985           6
4      310620 1988           2
5      310640 1988           0
6      310670 2017           3

I would like that each value in my column "Ano" become a column. I tryed to execute a code using tidyr, but I did not have sucess:

Num_casos_Sar <- Num_casos_Sar %>%
  separate(Ano, into = paste("Ano", seq_along(Ano), sep = ""), sep = "")
2
  • 3
    Please show the output you expect for this sample input. it sounds like you are trying to reshape from long to wide stackoverflow.com/questions/5890584/… but more clarity would be helpful
    – MrFlick
    Commented Apr 5, 2024 at 18:39
  • This seems like "pivot from long to wide". Try tidyr::pivot_wider(Num_casos_Sar, id_cols = "Cod_municip", names_from = "Ano", values_from = "Not_Sarampo"), and see MrFlick's link as well as stackoverflow.com/q/11608167/3358272 for more discussion/examples.
    – r2evans
    Commented Apr 5, 2024 at 18:47

1 Answer 1

0

The str_split() function in the stringr library could get that done like so

df[c('Ano1','Ano2','Ano3','Ano4')] <- data.frame(do.call(rbind, str_split(as.character(df$ano),'')))

Data:

Cod_municip <- c(310110,310160,310350,310620,310640,310670)
Ano <- c(1989,1988,1985,1988,1988,2017)
Not_Sarampo <- c(3,0,6,2,0,3)
df <- data.frame(Cod_municip,Ano,Not_Sarampo)

Output:

  Cod_municip  Ano Not_Sarampo Ano1 Ano2 Ano3 Ano4
1      310110 1989           3    1    9    8    9
2      310160 1988           0    1    9    8    8
3      310350 1985           6    1    9    8    5
4      310620 1988           2    1    9    8    8
5      310640 1988           0    1    9    8    8
6      310670 2017           3    2    0    1    7

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.