我有一个数据框中的列是字符类型。变量包括1、01、2、01、3、03、4、04等混合数字。
如何选择所有没有前导'0'的内容,并格式化为01、02、03、04等等。
数字
,然后使用sprintf
。df1$col1 <- sprintf("%02d", as.numeric(df1$col1))
df1$col1
#[1] "01" "01" "02" "01" "03" "03" "04" "04"
df1$col1 <- sprintf("%02d", as.numeric(as.character(df1$col1)))
df1$col1 <- c(1, '01', 2, '01', 3, 'A', 4, '04')
i1 <- grepl("^[0-9]$", df1$col1)
df1$col1[i1] <- paste0("0", df1$col1[i1])
df1$col1
#[1] "01" "01" "02" "01" "03" "A" "04" "04"
df1 <- data.frame(col1 = c(1, '01', 2, '01', 3, '03', 4, '04'), stringsAsFactors=FALSE)
vec<-c("01","1","2","03","05","3","4","A","B","XX")
>vec
[1] "01" "1" "2" "03" "05" "3" "4" "A" "B" "XX"
现在:
ifelse(nchar(vec)!=2,paste0("0",vec),vec)
[1] "01" "01" "02" "03" "05" "03" "04" "0A" "0B" "XX"
ifelse((nchar(vec)!=2 &!is.na(as.numeric(vec))) ,paste0("0",vec),vec)
[1] "01" "01" "02" "03" "05" "03" "04" "A" "B" "XX"
可能是一个数组或列表,其中包含了一些字符串元素。这个正则表达式的解决方案是在col1
是数字时插入一个0:
df1 <- data.frame(
col1 = c(1, '01', 2, '01', 3, '03', 4, '04','A','XX'),
stringsAsFactors = FALSE)
df1$col1 <- gsub("(\\d)+", "0\\1", df1$col1)
df1$col1
# [1] "01" "01" "02" "01" "03" "03" "04" "04" "A" "XX"
[1] "01" "01" "02" "01" "03" "0A" "04" "04"
- Jaapsprintf
在不同平台上存在差异,特别是在零填充和Windows方面。 - joran