使用R,需要知道如何将一列格式化为12位数字并将其格式化为xxxx_xxxx_xxxx。
#install.packages("tidyr")
#install.packages("readxl")
library(tidyr)
library(readxl)
projectToL4Raw <- read.csv("project_pro.csv")
projectToL4Raw
projectToL4RawSeparator <- separate(projectToL4Raw, ALLOCATION_CBD, c("CBD", "Cost Center"), sep = ":")
write.csv(projectToL4RawSeparator, file = "my_data.csv")
我导入了一个文件,其列号为'10021502'
。需要将该列的格式设置为000010021502
,然后再设置为0000_1002_1502
。
答案 0 :(得分:1)
给予
x <- '10021502'
我们可以使用formatC
获得所需的输出
formatC(
x = as.integer(x),
width = 12, # total width
flag = "0", # pads zeros at beginning
big.mark = "_", # mark between every big.interval before the decimal point
big.interval = 4 # see above
)
# [1] "0000_1002_1502"
答案 1 :(得分:0)
给出:
x <- '10021502'
以下将解决问题
gsub("([0-9]{4})([0-9]{4})", "0000_\\1_\\2", x)