R如何输出001,002,003等序号/编号?

需求

R默认带文本的编号不是按数字来排序的,这会对数据排序造成一定影响。如paste0("sample",1:10)在列中排序不是按1-100,而是按ASCII排序。

> sort(paste0("sample",1:10))
 [1] "sample1"  "sample10" "sample2"  "sample3"  "sample4"  "sample5"  "sample6"  "sample7"  "sample8"  "sample9" 

要想按数字排序,需要首先编制如01,02,03......等序号,再与文本进行合并。

formatC函数解决

> num <- formatC(1:10, flag = '0', width = 2)
> num
 [1] "01" "02" "03" "04" "05" "06" "07" "08" "09" "10"
> sort(paste0("sample",num))
 [1] "sample01" "sample02" "sample03" "sample04" "sample05" "sample06" "sample07" "sample08" "sample09" "sample10"

https://zhidao.baidu.com/question/1638492141117470980.html

你可能感兴趣的:(R如何输出001,002,003等序号/编号?)