7

I would like to know how to keep ordering after spread.

data<-tibble(var=c("A","C","D","B"), score=c(1,2,4,3))

data_spread <-data%>%spread(key = var, value = score)

I would like to keep the order of c("A","C","D","B").

user224050
  • 317
  • 3
  • 10

1 Answers1

8

An option is to convert to factor with levels specified as the unique elements of 'var' will make sure the order is the order of occurrence

library(dplyr)
library(tidyr)
data %>% 
      mutate(var = factor(var, levels = unique(var))) %>%
      spread(var, score)
# A tibble: 1 x 4
#      A     C     D     B
#  <dbl> <dbl> <dbl> <dbl>
#1     1     2     4     3
akrun
  • 874,273
  • 37
  • 540
  • 662