how to keep ordering after spread
Asked Answered
A

1

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

Ankledeep answered 15/8, 2019 at 18:42 Comment(0)
Q
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
Quirt answered 15/8, 2019 at 18:43 Comment(1)
Thank you so much!!Ankledeep

© 2022 - 2024 — McMap. All rights reserved.