R save matrix to csv and load as matrix

I have a very large matrix and I want to store it locally 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's 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, there are several formatting issues here, including the title and quotes are misplaced. Any insight on how to keep this matrix in process? Thank!

+3


source to share


1 answer


One option that might suit your needs is to use a function save()

that will allow you to store your matrix on disk without worrying about formatting issues:

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

      



If you want to load this matrix again, you can use load()

with the name of the generated data file:

load("copy_fourgram.RData")

      

+5


source







All Articles