[R] sum multiple csv files

Jeff Newmiller jdnewmil at dcn.davis.ca.us
Mon Jan 15 17:35:23 CET 2018

Your message seems unclear, and as evidence the respondents are giving various answers. You should provide a small sample of input and output data as it would look in R to avoid this kind of thrashing about. See [1][2][3] for guidance. Note that you also really need to figure out how to make sure your email program sends plain text, because HTML formatting WILL be stripped by the mailing list (read the Posting Guide) and that process often garbles it. 

My own possibly-confused reading of your question ("each cvs file has 47 rows and colunms, so the final data frame should have the same") is that you do not yet understand the difference between matrices and data frames ([4]), and you want to perform matrix (element-wise) addition. This would require that you convert the data frames read in by read.csv into matrices before adding them:

All_data <- lapply(filenames
###read cvs files and add the row and column names to each data frame
 as.matrix( read.csv(i, header=FALSE, sep = "", col.names = col_names, row.names = row_names)

result <- Reduce( `+`, All_data )

This will fail if any of the values in your csv files are non-numeric, but dealing with that would require us to know specifics about your files or intent that you have omitted. (The dput function is indispensable for clarifying such issues [1][2].)

[1] http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example

[2] http://adv-r.had.co.nz/Reproducibility.html

[3] https://cran.r-project.org/web/packages/reprex/index.html (read the vignette)

[4] see "Introduction to R" (part of the R documentation)

Sent from my phone. Please excuse my brevity.

On January 15, 2018 1:29:05 AM PST, Alejandra Lopez-Galan <alejandra7galan at gmail.com> wrote:
>Hi, I am pretty new to R and I would apreciatte very much your help to
>solve my problem. I have 40 csv files that have the same structure, and
>want to merge them into a single data frame.
>I already have load and combined all the cvs files into a large list,
>and I
>created two
>filenames <- list.files('data',full.names=TRUE)
>All_data <- lapply(filenames,function(i){
>###read cvs files and add the row and column names to each data
> read.csv(i, header=FALSE, sep = "", col.names = col_names, row.names =
> })
>However I would like to sum the rows of cvs files to get a single data
>frame (each cvs file has 47 rows and colunms, so the final data frame
>should have the same). I could only do it one by one data data frame,
>but I
>was wondering if anyone could give an idea of how to write a function
>	[[alternative HTML version deleted]]
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>PLEASE do read the posting guide
>and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list