简体   繁体   中英

Append a vector as a row in a CSV file

What I already have:

Consider the following data — just dummy data, the real data is created automatically:

features <- numeric(0)
features <- c(features, 1, 2, 3, 4, 5, 6)
features2 <- numeric(0)
features2 <- c(features2, 1, 2, 3, 4, 5, 6)
featureVectors <- list()
featureVectors[["file1"]] <- features
featureVectors[["file2"]] <- features2
resultMatrix <- do.call(rbind, featureVectors)
colnames(resultMatrix) <- c("SPEC_MEAN", "SPEC_SD", "SPEC_MODE", "AUTOC_MEAN", "AUTOC_SD", "ZC_MEAN")

This produces an output like the following:

      SPEC_MEAN SPEC_SD SPEC_MODE AUTOC_MEAN AUTOC_SD ZC_MEAN
file1         1       2         3          4        5       6
file2         1       2         3          4        5       6

I can write this to a CSV file by calling write.csv(resultMatrix, file="out.csv") .


What I need:

As the result file is (currently) just created on the fly, I'd like to write these features (ie the vectors) to the CSV file as soon they are evaluated.

So I thought I'd use write.csv and append , but the option isn't available for the method. I then thought I could use write.table , but there are two problems:

  1. write.table does not indent the first empty column name, thus leaving my first row shifted one to the left.

  2. The data is somehow incorrectly transposed. See example below.


What I've tried:

Also, calling these commands …

write.table(resultMatrix, file="data-appended.csv", sep=",")
write.table(features, file="data-appended.csv", sep=",", append=TRUE, col.names=FALSE)

… produces this result:

"SPEC_MEAN","SPEC_SD","SPEC_MODE","AUTOC_MEAN","AUTOC_SD","ZC_MEAN"
"file1",1,2,3,4,5,6
"file2",1,2,3,4,5,6
"1",1
"2",2
"3",3
"4",4
"5",5
"6",6

… which is not what I want. So, how do I append the content of the features vector, including the file name, to an already existing CSV file?

Two adjustments will solve your two problems.

  • To keep indentation of the column headers, use the unintuitive (but documented!) argument col.names=NA :

     write.table(resultMatrix, file = "data-appended.csv", sep = ",", col.names = NA) 
  • To write features (a vector) as a row rather than a column, transpose it and convert it to a matrix before passing it to write.table() :

     FF <- as.matrix(t(features)) write.table(FF, file = "data-appended.csv", sep = ",", col.names = FALSE, append=TRUE) 

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