I have written code to previously generate time series data from a model for multiple files. I need the full time series data in general, but I also want to read in the results for all columns from specific days and combine them into a separate file. However, when I do this, I get "Error in rbind(deparse.level, ...) : numbers of columns of arguments do not match" despite the fact that I know for a fact all files should have the same column names and # of columns.
I tried the approach here Select multiple rows in multiple DFs with loop in R but I got the error "Error in rbind(deparse.level, ...) : numbers of columns of arguments do not match"
Resfiles = list.files("C:/Users/Me/Desktop/R Code/Testfiles", pattern = "Results+.*csv")
Resfiles
is how I am reading in the files
Approach 1:
resfiles.list = sapply(Resfiles, function(file)
{df = read.csv(file, header=TRUE, stringsAsFactors=FALSE)
df$SourceFile = file
enddate = nrow(file)
df = df[c(1,2,21,133,159,enddate), ]
}
)
allres = do.call(rbind, resfiles.list)
generates the error "Error in rbind(deparse.level, ...) : numbers of columns of arguments do not match"
and Approach 2:
Results = NULL;
for(j in Resfiles)
{
input = read.csv(file = j, header = TRUE, sep =",")
enddate = nrow(input)
d0 = input[1, ]
d0
d1 = input[2, ]
d20 = input[21,]
d132=input[133, ]
d158 = input[159, ]
final = input[enddate, ]
final
results1o = rbind(d0, d1, d20, d132, d158, final)
Results = rbind(Results,results1o )
print(Results)
}
write.csv(Results, file = "PredResults.csv")
When I try Approach 2 with smartbind instead I get the error "Error in !sapply(data, function(l) is.null(l) | (ncol(l) == 0) | (nrow(l) == : invalid argument type"
If I just use rbind, I get "Error in read.table(file = file, header = header, sep = sep, quote = quote, : first five rows are empty: giving up"
What I would like to get is a data frame with the specific rows of interest grouped by animal that I can later subset and process as needed. I just need to be able to read in these 40-odd results files, extract the rows needed all into one big data frame, and save that as a csv and I need it extensible so that the same code will work whether I have 40ish files or >100.