R将Matrix保存到csv,并作为Matrix加载 [英] R save Matrix to csv, and load as 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"
这是我要保存的代码:
library(MASS)
write.matrix(format(copy_fourgram, scientific=FALSE),
file = paste("./en_US/ngrams/", "copy_fourgram.csv", sep="/"), sep=",")
当我读回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!
推荐答案
一个可能满足您需要的选项是使用save()
函数,该函数可让您将矩阵存储到磁盘上而不必担心格式问题:>
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")
要再次加载此矩阵时,可以将load()
与创建的数据文件的名称一起使用:
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")
这篇关于R将Matrix保存到csv,并作为Matrix加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!