我的数据框中的一列有如下数据:
"3,4"
"9,10"
"7,8,9"
"9,10,11,12,13,14"
如何将其格式化为以下格式:
"03,04"
"09,10"
"07,08,09"
"9,10,11,12,13,14"
答案 0 :(得分:0)
我们可以将数字与strsplit
分开,在将字符类转换为数字后使用sprintf
,最后将元素粘贴在一起
sapply(strsplit(df$V1, ','), function(x)
paste(sprintf("%02d", as.numeric(x)), collapse=","))
#[1] "03,04" "09,10" "07,08,09"
#[4] "09,10,11,12,13,14"
或者不按,
分割,我们可以使用regex
插入0
gsub('(?<=,)(?=([0-9],|[0-9]$))|^(?=[0-9],)',
"0", df$V1, perl=TRUE)
#[1] "03,04" "09,10" "07,08,09" "09,10,11,12,13,14"
df <- structure(list(V1 = c("3,4", "9,10", "7,8,9",
"9,10,11,12,13,14"
)), .Names = "V1", class = "data.frame",
row.names = c(NA, -4L))