简体   繁体   中英

adding two lines of text to a csv file in R

I am looking to add two lines to a csv file using R that I have created in a loop. I begin with a number of files, named file1.csv, file2.csv, etc, each of which contain two columns of coordinates. I then use these as index matrices to create new csv files that have a '2' listed in the entry in the index file, and a '0' otherwise. I add headers to the file, so that the resulting file looks like:

"","1","2","3","4","5"
"1",0,0,0,0,0
"2",0,0,0,0,2

which is exactly what I need (my code is below). However, I need to also add two rows to the beginning of the csv file that read "min 1" and "max 3", respectively, that come before the headers, so that it would look like:

"min 1",,,,
"max 3",,,,
"","1","2","3","4","5"
"1",0,0,0,0,0
"2",0,0,0,0,2

I've tried adding rows to the M matrix, rbinding, ,merging two csvs, reading the csv file back in and trying to add the rows then, and I'm not getting anything that works. Advice is much appreciated (as well as improving my existing code which I am sure is quite inelegant).

Thank you

 csvdat <- list.files(pattern='file.*.csv')
 for (i in seq_along(csvdat)){
data <- read.csv(csvdat[i])
data[,2] -> x
data[,3] -> y
index=cbind(x,y)   
a <- length(x)+1    
matrix(nrow=a,ncol=a) -> M
M[] <- 0
M[index] <- 2
Cn <- c(1:a)
colnames(M) <- Cn
file <- as.character(paste("matrix", i, ".csv", sep=""))
write.csv(M, file,col.names=TRUE)
}

This is a classic case of "what is the problem you are trying to solve?" If you explain what you're doing with the output file, and why it's constrained to be in such an odd configuration, someone can probably explain a much better way to achieve your final desired result -- not just produce this particular csv file.

That said, in general you can use write or write.csv to send your "min 1,min 3" string to a file, followed by write.csv(data,{other arguments},append=TRUE) to place your matrix of data below the string(s).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM