r - Implicit sorting in tidyr::spread and dplyr::summarise -


my data ordered observations , want keep ordering as possible while doing manipulations.

take answer this question, put "b" ahead of "a" in dataframe. resulting wide data sorted column "name", i.e., "a" first, "b".

df = data.frame(name=c("b","b","a","a"),                 group=c("g1","g2","g1","g2"),                 v1=c(10,40,20,30),                 v2=c(6,3,1,7))  gather(df, var, val, v1:v2) %>%  unite(varg, var, group) %>%  spread(varg, val)    name v1_g1 v1_g2 v2_g1 v2_g2 1       20    30     1     7 2    b    10    40     6     3 

is there way keep original ordering? this:

  name v1_g1 v1_g2 v2_g1 v2_g2 1    b    10    40     6     3 2       20    30     1     7 

04/02 edit: i've found dplyr::summarise sorting well. arrange(name, df$name) still works restore order. wonder if sorting necessary design of packages?

df %>%    group_by(name) %>%    summarise(n()) %>%     name n() 1      2 2    b   2 

you can sort name based on order in original data frame:

gather(df, var, val, v1:v2) %>%    unite(varg, var, group) %>%    spread(varg, val) %>%   arrange( order(match(name, df$name)))  #   name v1_g1 v1_g2 v2_g1 v2_g2 # 1    b    10    40     6     3 # 2       20    30     1     7 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -