Sample code could be helpful here and also your desired outcome.
I have two big matrices: A and B. A contains all numbers and B contains strings. For purpose of writing to a file I do cbind on A and B and use 'write' command to push it into a csv file. It works fine but in csv file I see that it writes A matrix first and then starts writing B after right hand bottom cell.
How can I do it in a cleaner way?
Thanks
Sample code could be helpful here and also your desired outcome.
"If you torture the data long enough it will eventually confess."
-Ronald Harry Coase -
sak (03-05-2013)
Can you post an abbreviated example of the code you have, the output you want, and the output you currently get?
Edit: not fast enough, trinker beat me to it
A very simple example that I simulated is:
Sorry I think I lied earlier. The 1,3,4,5,6 are not printed starting in right-bottom cell but in the same column i.e. B is printed after A.Code:A = c('a','a','b','a','c') B = c(1,3,4,5,6) D = cbind(A,B) > D A B [1,] "a" "1" [2,] "a" "3" [3,] "b" "4" [4,] "a" "5" [5,] "c" "6" write(D,"C:\\OutTest.csv") When I open the csv, it looks as following: a a b a c 1 3 4 5 6
Try this method for writing to a file instead:
Code:write.table(D,"OutTest.csv", sep = ",", col.names = T, row.names=F, qmethod = "double")
"If you torture the data long enough it will eventually confess."
-Ronald Harry Coase -
Cool. It works.
Thanks
Matrices in R only hold one data type. You want to use a data.frame data type. It's essentially a list of equal length vectors that displays like a matrix. The nice part about that is that the vectors can now be different data types. If you have separate numeric and character vectors A and B, then simply do
Code:# You can have characters converted to factor data type if you prefer; defaults to TRUE x <- data.frame(nums = A, strings = B, stringsAsFactors = FALSE) # write.csv is just a wrapper for write.table with some select defaults, like sep = "," write.csv(x, "Output.csv", row.names = FALSE)
Simple yet very insightful answer especially good for a novice users like.
|
|