0

I currently have a data frame that looks as follows:

Week Publisher Perc
1 De Telegraaf 0.597
1 De Volkskrant 0.874
2 De Telegraaf 3.761
2 De Volkskrant 4.123

However, I want to have it like this:

Week TelegraafPerc VolkskrantPerc
1 0.597 0.874
2 3.761 4.123

I honestly have no clue in how to make

Publisher

into a Column and link it to the relevant

Perc

in order to sort it by

Week
data:

structure(list(Week = c(1L, 1L, 2L, 2L), Publisher = c("De Telegraaf", 
"De Volkskrant", "De Telegraaf", "De Volkskrant"), Perc = c(0.597, 
0.874, 3.761, 4.123)), class = "data.frame", row.names = c(NA, 
-4L))

jpsmith
  • 11,023
  • 5
  • 15
  • 36
  • 2
    We could use `pivot_wider`: `library(tidyr) library(dplyr) df %>% pivot_wider( names_from = Publisher, values_from =Perc )` – TarJae Jan 27 '23 at 17:30
  • These two analogous datasets are generally referred to as “long” and “wide” - as you continue to learn this terminology will be useful as you search for solutions. Good luck! – jpsmith Jan 27 '23 at 17:33
  • This is a dupe of https://stackoverflow.com/q/11608167/3358272. Two methods include: `tidyr::pivot_wider(dat, "Week", names_from = "Publisher", values_from = "Perc")` and `reshape2::dcast(Week ~ Publisher, data = dat, value.var = "Perc")`. – r2evans Jan 27 '23 at 17:37
  • Or you can use akrun's since-deleted `data.table` code: `dcast(setDT(df1), Week ~ Publisher, value.var = 'Perc')` (truncated for terseness, recognizing that this generates column names with spaces, just a _little_ more work to use them in R). – r2evans Jan 27 '23 at 18:35

0 Answers0