1

This may be a very common problem, so I am specifically looking for an elegant or at least less-kludgy-than-mine solution.

I have series of files from 001.csv to 200.csv. I need to be able to select which ones I want in a function such that a list is passed and only the appropriate list is selected.

function(filenumbers = 1:200 {
}

I have created a very ugly set of if statements to provide the '00' and '0' prefixes where necessary:

for (i in filenumbers) {
if (i < 10) {filename<-paste("00", i, ".csv", sep ="")
} else if (i < 100) {filename<-paste("0", i, ".csv", sep="")
} else {filename<-paste(i, ".csv", sep="")}
print(filename)
}

This does output the correct list of names, but it seems like there must be a better way to handle this problem. I am somewhat new to R, so any over-explanation would be appreciated.

2 Answers 2

2

This would be a good use of the sprintf function. It has many formatting options, but for this case I would use

sprintf("%03d.csv", 1:200)

#   [1] "001.csv" "002.csv" "003.csv" "004.csv" "005.csv"
#   [6] "006.csv" "007.csv" "008.csv" "009.csv" "010.csv"
#     ...
#  [96] "096.csv" "097.csv" "098.csv" "099.csv" "100.csv"
# [101] "101.csv" "102.csv" "103.csv" "104.csv" "105.csv"
#     ...
# [191] "191.csv" "192.csv" "193.csv" "194.csv" "195.csv"
# [196] "196.csv" "197.csv" "198.csv" "199.csv" "200.csv"
Sign up to request clarification or add additional context in comments.

Comments

1

A combination of formatC() and paste0() should work:

paste0(formatC(1:200, width = 3, format = "d", flag = 0), ".csv")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.