Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R save Matrix to csv, and load as Matrix

Tags:

r

csv

matrix

I have a very large matrix, and want to save to local for later use. Here is my matrix:

head(copy_fourgram)
[,1]     [,2]    [,3]      [,4]      [,5]
[1,] "\u0097" "a"     "moment"  "when"    "1" 
[2,] "\u0096" "and"   "of"      "support" "1" 
[3,] "\u0095" "eli"   "lathrop" "yard"    "1" 
[4,] "\u0095" "james" "brown"   "yard"    "1" 
[5,] "\u0095" "keep"  "a"       "fire"    "1" 
[6,] "\u0097" "maybe" "even"    "vent"    "1" 

Here is my code to save:

library(MASS)
write.matrix(format(copy_fourgram, scientific=FALSE), 
           file = paste("./en_US/ngrams/", "copy_fourgram.csv", sep="/"), sep=",") 

When I read back as csv:

fourgram_file <- file("./en_US/ngrams/fourgram.csv", "r")
new_copy_fourgram <- read.csv(fourgram_file, header=T)
close(fourgram_file)
new_copy_fourgram <- as.matrix(new_copy_fourgram)
head(new_copy_fourgram)
     X.                             a                       moment     X1                     when                          
[1,] "\u0096                      " "and                    " "of      "1"                     " "support                     "
[2,] "\u0095                      " "eli                    " "lathrop "1"                   " "yard                        "
[3,] "\u0095                      " "james                  " "brown   "1"                    " "yard                        "
[4,] "\u0095                      " "keep                   " "a       "1"                        " "fire                        "
[5,] "\u0097                      " "maybe                  " "even    "1"                   " "vent                        "
[6,] "½                           " "years                  " "old     "1"                        " "now                         "

As you can see, I have multiple formatting issues here, including header and quotations misplaced. Any insight on how to preserve this matrix through the process? Thank you!

like image 237
jKraut Avatar asked Oct 25 '25 11:10

jKraut


1 Answers

One option which may suit your needs is to use the save() function which would allow you to store your matrix to disk without worrying about formatting issues:

save(copy_fourgram, file = "copy_fourgram.RData")

When you want to load this matrix again, you can use load() with the name of the data file you created:

load("copy_fourgram.RData")
like image 165
Tim Biegeleisen Avatar answered Oct 28 '25 00:10

Tim Biegeleisen