dimanche 21 juin 2020

R - Entering a sequence of number in if loop follows only one condition [duplicate]

I am making a function which puts leading zeroes to number to make it a 3-digit string and adding .csv to each. This is my code

filename <- function(id) {
  
  if (id<10) {
    file_name=paste("00",id,".csv", sep="")
  }
  else if (id<100) {
    file_name=paste("0",id,".csv", sep="")
  }
  else  {
    file_name=paste(id,".csv", sep="")
    }
  file_name
}

When I entered filename(1:12), the following was the output

the condition has length > 1 and only the first element will be used [1] "001.csv"  "002.csv"  "003.csv"  "004.csv"  "005.csv"  "006.csv"  "007.csv"  "008.csv"  "009.csv"  "0010.csv"
[11] "0011.csv" "0012.csv"

Basically my problem is that once the id comes to 10, it still follows the 1st if condition. When it comes to id=10 and higher, the supposed output should be 010.csv and so on. How can I fix my code?

Aucun commentaire:

Enregistrer un commentaire