0

How would I achieve the following with tidyverse syntax?

set.seed(1)
d <- data.frame(prd     = rep(paste0("P", 1:5), 2),
                cluster = rep(paste0("Cluster", 1:2), each = 5),
                class   = c("l", "l", "m", "h", "h", "l", "m", "m", "h", "h"),
                score   = c(1:5, 11:15))
d <- d[sample(NROW(d)), ] ## in order to not assume any pre-order
reshape(d, idvar = "prd", timevar = "cluster", direction = "wide")
#   prd class.Cluster1 score.Cluster1 class.Cluster2 score.Cluster2
# 3  P3              m              3              m             13
# 4  P4              h              4              h             14
# 5  P5              h              5              h             15
# 7  P2              l              2              m             12
# 6  P1              l              1              l             11

The closest I came was:

library(tidyverse)
d %>% spread(score, cluster)
#   prd class Cluster1 Cluster2
# 1  P1     l        1       11
# 2  P2     l        2       NA
# 3  P2     m       NA       12
# 4  P3     m        3       13
# 5  P4     h        4       14
# 6  P5     h        5       15

So I would like to spread both columns class and score simultaneously. How would I do that in tidyverse?

thothal
  • 16,690
  • 3
  • 36
  • 71
  • Just curious... why not stick with reshape() if it works well for you? – s_baldur Nov 21 '18 at 15:55
  • Well, I would say consistency. I do all of my data transformation with one `tidyverse` so I would like to stick to it also for this case. – thothal Nov 21 '18 at 16:51

1 Answers1

1

With tidyr:

library(tidyverse)

d %>%
  gather(var, value, class:score) %>%
  unite(var, var, cluster, sep = ".") %>%
  spread(var, value)

Output:

  prd class.Cluster1 class.Cluster2 score.Cluster1
1  P1              l              l              1
2  P2              l              m              2
3  P3              m              m              3
4  P4              h              h              4
5  P5              h              h              5
  score.Cluster2
1             11
2             12
3             13
4             14
5             15
acylam
  • 18,231
  • 5
  • 36
  • 45