问题描述
我想实现我 write.csv 的文件与我用于 read.csv2 的文件同名。见下文:我正在读取文件名“2005Calc.csv”并想将其写为: “2005Calc28-01-2021.csv”。我怎样才能做到这一点?我在下面尝试了一些东西并且它有效..只是我无法向其中添加 csv 文件名。
提前致谢。
LKCalc <- read.csv2("2005Calc.csv")
date<-format(Sys.time(),"%d-%m-%Y")
csvFileName <- paste("FILENAME",date,".csv",sep="")
write.csv(LKCalc,file=csvFileName)
解决方法
函数 list.files()
(documentation) 将为您提供与给定 pattern
匹配的所有文件的文件名(如果未提供,则为所有文件)。
"FILENAME"
是文字字符串,而不是引用文件名的变量。怎么样(未经测试):
FILENAME <- "2005Calc"
LKCalc <- read.csv2(paste0(FILENAME,".csv"))
date <- format(Sys.time(),"%d-%m-%Y")
csvFileName <- paste0(FILENAME,date,".csv")
write.csv(LKCalc,file=csvFileName)
,
这是一个无需提供名称的解决方案:
# Read in your data
LKCalc <- read.csv2("C:/YOUR PATH.csv")
# Create date character vector
date<-format(Sys.time(),"%d-%m-%Y")
# Pull names from the path you specify (this should be where your document(s) live)
# If you have more than one .csv,you will need to iterate over names,or figure out a way to modify.
# This is only to illustrate how this might be done
name <- list.files(path = "C:",pattern = ".csv")
# Remove ".csv" from the name
name <- sub(".csv$","",name)
# Create the file name
csvFileName <- paste0(name,".csv")
# Write out
write.csv(LKCalc,file=csvFileName)