Help with data arrangement

I would like to ask for help.

My file includes data about number of ticker in each month in 10 years. I would like to rearrange my data to check the ticker in each month of each year.
My sample data is like that. I would like to have an arrangement like a picture below.
I appreciate any helps. Thank you in advance.

data<-data.frame(

year = c(2006L,2006L,2006L,2006L,2006L,2006L,

2006L,2006L,2006L,2007L,2007L,2007L,2007L,2007L,2007L,

2007L,2007L,2007L),

month = c(1L,1L,1L,1L,2L,2L,2L,3L,3L,1L,1L,

2L,2L,3L,3L,3L,3L,3L),

ticker = as.factor(c("AGF","BBC","BBS",

"BPC","AGF","BBC","BBS","BBC","AGF","AGF","BBS",

"AGF","CAN","AGF","BBC","BBS","BPC","CAN"))

)

I would recommend to you the tidyverse library, which includes within it a pivot_wider function you could use for such a purpose.

Thank you. I tried, but I am so confused and can not get the result as I want.

please share the code that you tried, and try to explain to your best ability the source of your confusion

One of my friend (Štěpán Mikula) help me with this problem. This is the code for my problem

data %>%
group_by(year,month) %>%
mutate(
rn = row_number()
) %>%
ungroup() %>%
pivot_wider(
names_from = rn,
values_from = ticker
) %>%
mutate(across(everything(), as.character)) %>%
mutate(id = str_c(year,"_",month)) %>%
pivot_longer(-id) %>%
complete(id,name) %>%
pivot_wider(names_from = id) %>%
arrange(name)

Thank you so much.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.