0

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?

2 Answers2

0

The issue is that your function is not vectorized, i.e. the if-condition uses only the first element of 1:12 (= 1) to check the condition. Using stringr::str_pad you can achieve your desired result like so:

paste0(stringr::str_pad(1:12, width = 3, pad = "0"), ".csv")
stefan
  • 90,330
  • 6
  • 25
  • 51
0

Import strings library(stringr)

define all filenames

filename<-seq(1:12)

Write a function Y which returns 3 digit name

Y<-function(id){
  paste(stringr::str_pad(id, width=3, pad="0"),".csv", sep="")
  
}

use apply to call it

lapply(filename,Y)