After unite() arrange() organized SeqNum like so 1, 10, 11, ..., 19, 2, 20, ...
jj <- data.frame(TrainNum = 2100, SeqNum = 1:30) jj %>% unite(tnSn, TrainNum, SeqNum) %>% arrange(tnSn)
Has anyone found a work around?
This is a little hacky, but you could do this:
library(tidyverse) jj <- data.frame(TrainNum = 2100, SeqNum = 1:30) jj %>% mutate(SeqNum = ifelse(SeqNum < 10, paste0("0", SeqNum), SeqNum)) %>% unite(tnSn, TrainNum, SeqNum) %>% arrange(tnSn) #> tnSn #> 1 2100_01 #> 2 2100_02 #> 3 2100_03 #> 4 2100_04 #> 5 2100_05 #> 6 2100_06 #> 7 2100_07 #> 8 2100_08 #> 9 2100_09 #> 10 2100_10 #> 11 2100_11 #> 12 2100_12 #> 13 2100_13 #> 14 2100_14 #> 15 2100_15 #> 16 2100_16 #> 17 2100_17 #> 18 2100_18 #> 19 2100_19 #> 20 2100_20 #> 21 2100_21 #> 22 2100_22 #> 23 2100_23 #> 24 2100_24 #> 25 2100_25 #> 26 2100_26 #> 27 2100_27 #> 28 2100_28 #> 29 2100_29 #> 30 2100_30
Created on 2018-11-20 by the reprex package (v0.2.1)
Oh look, there's also tidyverse function, stringr::str_pad() that can help here! Could be useful if you had numbers larger than 2 digits!
tidyverse
stringr::str_pad()
library(tidyverse) jj <- data.frame(TrainNum = 2100, SeqNum = 1:30) jj %>% mutate(SeqNum = str_pad(SeqNum, width = 2, pad = "0")) %>% unite(tnSn, TrainNum, SeqNum) %>% arrange(tnSn) #> tnSn #> 1 2100_01 #> 2 2100_02 #> 3 2100_03 #> 4 2100_04 #> 5 2100_05 #> 6 2100_06 #> 7 2100_07 #> 8 2100_08 #> 9 2100_09 #> 10 2100_10 #> 11 2100_11 #> 12 2100_12 #> 13 2100_13 #> 14 2100_14 #> 15 2100_15 #> 16 2100_16 #> 17 2100_17 #> 18 2100_18 #> 19 2100_19 #> 20 2100_20 #> 21 2100_21 #> 22 2100_22 #> 23 2100_23 #> 24 2100_24 #> 25 2100_25 #> 26 2100_26 #> 27 2100_27 #> 28 2100_28 #> 29 2100_29 #> 30 2100_30
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.