简体   繁体   English

R中read.csv的可变文件名

[英]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. 我有001.csv到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: 我创建了一组非常丑陋的if语句,在必要时提供'00'和'0'前缀:

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. 我对R有点新,所以任何过度解释都会受到赞赏。

This would be a good use of the sprintf function. 这将很好地利用sprintf函数。 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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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