Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change column variable string from "1" to "01"

Tags:

dataframe

r

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

like image 518
Justin Avatar asked Oct 26 '25 10:10

Justin


2 Answers

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"

data

df1 <- data.frame(col1 = c(1, '01', 2, '01', 3, '03', 4, '04'), stringsAsFactors=FALSE)
like image 56
akrun Avatar answered Oct 29 '25 02:10

akrun


 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"

EDIT (check only numeric ones. Leave characters unchanged)

 ifelse((nchar(vec)!=2 &!is.na(as.numeric(vec))) ,paste0("0",vec),vec)

[1] "01" "01" "02" "03" "05" "03" "04" "A" "B" "XX"

like image 36
amonk Avatar answered Oct 29 '25 00:10

amonk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!