I defined a function to process each csv file and it returns a matrix. I would like to use this function in a for loop to process all the files and combine all the data into one big matrix. But it seems this code does not work.
filenames=dir()
bigMatrix = processEachCSV(filenames[1])
for (i in 2:length(filenames1)) {
x = processEachCSV(filenames[i])
bigMatrix=rbind[bigMatrix,x]
}
I guess it is because I can not rbind x and bigMatrix and assign it to bigMatrix itself?
What shall I do instead?
The processEachCSV functions is like this:
processEachCSV <- function (filename){
x = read.table(filename, header=F, sep=',', fileEncoding='UTF-8')
x$V4=as.numeric(gsub("[^0-9.]",'', as.character(x$V4)))
x$V5=as.numeric(gsub("[^0-9.]",'', as.character(x$V5)))
x$V6=substr(filename, 1, nchar(filename)-4)
colnames(x)=c('DateTime','Site','AQI','PM25','PM10','City')
x=as.matrix(x)
return (x)
}
The basic approach would be something like:
do.call(rbind, lapply(filenames, read.csv))
Customize the read.csv
part with whatever you actually do with your processEachCSV
function (if that is indeed a function).
Alternatively, you can look at some of the rbind_list
function from "dplyr" or the rbindlist
function from "data.table", both of which are more efficient than do.call(rbind, ...)
. The result would not be a matrix
in those cases, but you can convert it to a matrix quite easily.
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.