如何在R数据帧中添加不同长度的前导零

时间:2016-07-20 21:36:14

标签: r dataframe

我有一个数据框,其中行名称的总位数不同。共有152行。当不同行需要不同数量的潜在客户以达到最多8位数时,如何添加前导零?

row.names
4921103 
42106   
19562106    
11102
3435467

2 个答案:

答案 0 :(得分:3)

我们可以尝试使用sprintf(假设示例中的row.names为数字)

sprintf("%08d", df1$row.names)
#[1] "04921103" "00042106" "19562106" "00011102" "03435467"

如果不是数字,请转换为数字并使用sprintf

sprintf("%08d", as.numeric(df1$row.names))

如果我们将row.names表示为数据集的rownames

row.names(df2) <- sprintf("%08d", as.numeric(row.names(df2)))
row.names(df2)
#[1] "04921103" "00042106" "19562106" "00011102" "03435467"

注意:无需外部包。

数据

df1 <- structure(list(row.names = c(4921103L, 42106L, 19562106L, 11102L, 
3435467L)), .Names = "row.names", class = "data.frame", row.names = c(NA, 
-5L))

df2 <- data.frame(v1= 1:5)
row.names(df2) <-  c(4921103L, 42106L, 19562106L, 11102L, 3435467L)

答案 1 :(得分:0)

使用stringr

# If row.names is a column
stringr::str_pad(df$row.names, 8, side = "left", pad = 0)

# If row.names means row names of the dataframe  
stringr::str_pad(row.names(df), 8, side = "left", pad = 0)

[1] "04921103" "00042106" "19562106" "00011102" "03435467"

检查:

abc <- data.frame(A = rep(NA, 5))
row.names(abc) <- c(4921103, 42106, 19562106, 11102, 3435467)

abc
          A
4921103  NA
42106    NA
19562106 NA
11102    NA
3435467  NA

row.names(abc) <- stringr::str_pad(row.names(abc), 8, side = "left", pad = 0)

abc 

          A
04921103 NA
00042106 NA
19562106 NA
00011102 NA
03435467 NA