1

So I have a table that is in the following format:

date <- c('t1','t1','t1','t2','t2','t2')
factor <- c('a','b','c','a','b','c')
beta <- c(1,2,4,3,5,2)

df <- data.frame(date, factor, beta)
df

 date factor beta
1   t1      a    1
2   t1      b    2
3   t1      c    4
4   t2      a    3
5   t2      b    5
6   t2      c    2

I want to reformat the data in the table in the following way:

date <- c('t1','t2')
factor_a <- c(1,3)
factor_b <- c(2,5)
factor_c <- c(4,9)

df <- data.frame(date, factor_a, factor_b, factor_c)

df
  date factor_a factor_b factor_c
1   t1        1        2        4
2   t2        3        5        9

I tried to use melt and reshape but I haven't been successful.

Erwin Rhine
  • 303
  • 2
  • 11

1 Answers1

2

We can use spread

library(tidyverse)
df %>% 
   mutate(factor = paste0("factor_", factor)) %>%
   spread(factor, beta)
#    date factor_a factor_b factor_c
#1   t1        1        2        4
#2   t2        3        5        2
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks for the help, since I'm applying this to a different data frame than the simple example above. I'm getting this error: Error: Column `factor` can't be modified because it's a grouping variable. – Erwin Rhine Mar 27 '19 at 22:03
  • @ErwinRhine Can you do `df %>% ungroup %>% mutate(..` – akrun Mar 28 '19 at 06:26