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")
.
As the result file is (currently) just created on the fly, I'd like to write these features
(i.e. 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:
write.table
does not indent the first empty column name, thus leaving my first row shifted one to the left.
The data is somehow incorrectly transposed. See example below.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With