0

Say that I have a dataframe with a column that has values that are either three or four numbers in length. What I want to do, is that whenever length = 3, I want to insert a 0 (zero) at the start of the number, for all values in the column, like this:

320 -> 0320
0672 -> 0672
120 -> 0120

Is there any way to do this? I thought of some kind of for-loop for this, but that may be unnecessarily complicated... (I am quite new to programming in general).

for ( i in dataset$col_name){
 if (nchar(dataset$col_name == 3)){
  dataset$col_name <- 0 + dataset$col_name
 } else {
  dataset$col_name <- dataset$col_name
 }
}

Thanks for help!

Haakonkas
  • 961
  • 9
  • 26
  • 1
    Have u tried `sprintf` i.e. `sprintf("%04d", as.numeric(c(320, "0672", 120)))` or use `library(stringr);str_pad(c("320", "0672", "120"), 4, pad = 0)` – akrun Aug 23 '17 at 09:18
  • Does this also work on a dataframe where i do not know the values that I want to change, only the length? (The dataframe contains over 4000 entries of various 3 and 4 length numbers) – Haakonkas Aug 23 '17 at 09:23
  • Yes, it would work. i.e. `sprintf("%04d", as.numeric(dataset$col_name))` – akrun Aug 23 '17 at 09:25
  • 1
    Thank you! This worked perfectly – Haakonkas Sep 05 '17 at 12:03

0 Answers0