【发布时间】:2015-01-28 17:15:51
【问题描述】:
我正在从某个文件夹中读取 csv 文件,这些文件都具有相同的结构。此外,我还创建了一个函数,可以将某个值添加到 dataFrame。
我已经创建了“文件夹阅读”部分,还创建了函数。但是,我现在需要将这两者相互连接。这就是我遇到问题的地方:
这是我的代码:
addValue <- function(valueToAdd, df.file, writterPath) {
df.file$result <- df.file$Value + valueToAdd
x <- x + 1
df.file <- as.data.frame(do.call(cbind, df.file))
fullFilePath <- paste(writterPath, x , "myFile.csv", sep="")
write.csv(as.data.frame(df.file), fullFilePath)
}
#1.reading R files
path <- "C:/Users/RFiles/files/"
files <- list.files(path=path, pattern="*.csv")
for(file in files)
{
perpos <- which(strsplit(file, "")[[1]]==".")
assign(
gsub(" ","",substr(file, 1, perpos-1)),
read.csv(paste(path,file,sep="")))
}
#2.appyling function
writterPath <- "C:/Users/RFiles/files/results/"
addValue(2, sys, writterPath)
如何在我的#1.reading R files 构造中应用addValue() 函数?有什么建议吗?
感谢您的回答!
更新
在试用示例代码时,我得到:
+ }
+ ## If you really need to change filenames with numbers,
+ newfname <- file.path(npath, paste0(x, basename(fname)))
+ ## otherwise just use `file.path(npath, basename(fname))`.
+
+ ## (4) Write back to a different file location:
+ write.csv(newdat, file = newfname, row.names = FALSE)
+ }
Error in `$<-.data.frame`(`*tmp*`, "results", value = numeric(0)) :
replacement has 0 rows, data has 11
有什么建议吗?
【问题讨论】:
-
你有什么问题? (您在致电
list.files()时需要full.names=TRUE吗?) -
@r2evans 感谢您的回复!我的问题是我不知道如何将我的函数
addValue()应用于我的1.reading R files构造? atm 这两个是完全分开的......
标签: r statistics