I have a column in a dataframe that is a charachter type. The variables are a mix of 1, 01, 2, 01, 3, 03, 4, 04 etc.
How would I select all without a leading '0' and format so they are all 01, 02, 03, 04 etc
We need to first convert it to numeric and use sprintf
df1$col1 <- sprintf("%02d", as.numeric(df1$col1))
df1$col1
#[1] "01" "01" "02" "01" "03" "03" "04" "04"
If it is a factor column, first convert to character before heading to numeric
df1$col1 <- sprintf("%02d", as.numeric(as.character(df1$col1)))
If there are LETTERS included
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"
Then:
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With