0

I'm very new to R and i am troubled with transforming dataframe.

so i have

**user**    **category**    **Frequency**
John        Sports            2
John        Finance           3
Dave        Health            1
Kirby       Sports            1
Kirby       Health            4

but i want it to be

**user**    **Sports**    **Finance**    **Health**
John          2             3              0
Dave          0             0              1
Kirby         1             0              4

anyone can help?

pogibas
  • 27,303
  • 19
  • 84
  • 117

1 Answers1

0

You want some tidyr in your life:

df_long <-
  tibble::tribble(~user,    ~category, ~Frequency,
                 'John',   'Sports',          2,
                 'John',  'Finance',          3,
                 'Dave',   'Health',          1,
                'Kirby',   'Sports',          1,
                'Kirby',   'Health',          4)

df_wide <- tidyr::spread(data = df_long, key = category, value = Frequency, fill = 0)

So the Key is the column that becomes the new column names, and the value is the column that fills in the values below them. tidyr::gather does the opposite.

obrl_soil
  • 1,104
  • 12
  • 24