[英]Obtaining results from operations on multiple files as a two-column matrix
I'm using a for-loop to loop through files in a directory. 我正在使用for循环遍历目录中的文件。 Then I do a set of processing on the data in each file and write a matrix with 10 rows.
然后,我对每个文件中的数据进行一组处理,并编写一个包含10行的矩阵。 This is my code.
这是我的代码。
for(i in 1:length(testData))
{
MAE[1,i] = abs(forecastData$mean[i] - testData[i])
}
Now I wish to wish to do the following: 现在,我希望执行以下操作:
The number of rows for this matrix will be the total number of files in the directory(dynamically assigned is what I mean). 此矩阵的行数将是目录中文件的总数(动态分配是我的意思)。 How can I achieve this functionality?
如何实现此功能?
It is difficult to give a comprehensive answer because there is no example. 由于没有示例,因此很难给出全面的答案。 In general, however, I would use
list.files()
to obtain a vector of all the files in question, and then write a function that performed whatever math you need done on each file. 但是,总的来说,我将使用
list.files()
获得所有相关文件的向量,然后编写一个函数来执行您需要对每个文件进行的数学运算。 Such a function could look something like this. 这样的功能可能看起来像这样。
func.file_math <- function(file.name) {
<insert file operations>
return(list(file.name=file.name,
number=number))
}
Using sapply()
you could then run this over all the contents of your file.list()
. 使用
sapply()
然后你可以在你的所有内容运行此file.list()
Once done, you can simply use do.call()
and rbind.data.frame
to get a data frame of the results. 完成后,您只需使用
do.call()
和rbind.data.frame
即可获得结果的数据帧。
yourfiles <- list.files("/some/path/")
file_math <- sapply(X=yourfiles,
FUN=func.file_math,
simplify=FALSE,
USE.NAMES=TRUE)
file_math.df <- do.call(what=rbind.data.frame,
args=file_math)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.