简体   繁体   中英

variable file names for read.csv in R

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.

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"

formatC()paste0()应该有效:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM