Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to keep ordering after spread

Tags:

r

spread

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").

like image 347
user224050 Avatar asked Aug 15 '19 18:08

user224050


1 Answers

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
like image 75
akrun Avatar answered Nov 13 '22 23:11

akrun