首页 > 解决方案 > 使用 R 将矩阵保存到文件中

问题描述

我对 R 很陌生,我将不胜感激。

我需要计算一系列矩阵的特征值,然后将它们保存在单独的文件中。我的数据有 5 列和 10,000 行。为了能够计算这一点,我需要将数据分成一系列 5 x 5 矩阵。例如,请考虑一个只有 5 列和 10 行的数据集:

1 2 3 4 5
11 21 31 41 51
12 22 32 42 52
13 23 33 43 53
14 24 34 44 54
15 25 35 45 55
16 26 36 46 56
17 27 37 47 57
18 28 38 48 58
19 29 39 49 59 

到目前为止,我已经编写了以下代码:

R<-NULL
A <- setwd("c:/location of the file on this computer")
for (i in 0:1){
  X <- read.table(A, skip=i*5, nrow=5)
  M <- as.matrix(X)
  E <- eigen(M)
  R<-rbind(R,E)}
}

结果应该类似于: eigen() 分解

    $`values`
    [1]  2.362320e+02+0.000000e+00i -4.960046e+01+1.258757e+01i -4.960046e+01-1.258757e+01i  9.689475e-01+0.000000e+00i
    [5]  1.104994e-14+0.000000e+00i

$vectors
             [,1]                    [,2]                    [,3]           [,4]             [,5]
[1,] 0.9351696+0i  0.95959917+0.00000000i  0.95959917+0.00000000i  0.05003956+0i -1.529602e-15+0i
[2,] 0.1382999+0i -0.07952624-0.04585480i -0.07952624+0.04585480i -0.00162525+0i  4.670542e-17+0i
[3,] 0.1451493+0i -0.09392247-0.04970605i -0.09392247+0.04970605i -0.21235137+0i -4.082483e-01+0i
[4,] 0.2521091+0i  0.11157105+0.16033279i  0.11157105-0.16033279i -0.70990185+0i  8.164966e-01+0i
[5,] 0.1473217+0i -0.13518414-0.05496162i -0.13518414+0.05496162i  0.66965637+0i -4.082483e-01+0i

但是,我从当前代码中得到的结果是:

> class(R)
[1] "matrix"
> print(R)
  values    vectors   
E Complex,5 Complex,25
E Complex,5 Complex,25

我有几个问题,如果你能帮助解决其中任何一个问题,那将是一个很大的帮助:

  1. 如何解决我的问题?

  2. 此外,输出 Excel 文件(在临时文件夹中创建的文件)不会在 Excel 中打开。

标签: rexcelmatrix

解决方案


1)以上函数返回以下错误:无法打开文件'C:/此计算机上文件的位置':权限被拒绝。

我只是将文件移动到具有访问权限的目录,或者将文件的数据复制到另一个文件中。最后,使用 RStudio 功能导入数据。

2) 如何将循环结果保存到单独的文件中?在这种情况下,一个具有 5 列和 2 行的 Excel 文件(每个 5 x 5 矩阵有 5 个特征值)。

library(xlsx)
file <- paste(tempdir(), "./usarrests.xlsx", sep="")
res <- write.xlsx(USArrests, file) 

file您显示找到 xlsx 文件的路径。就我而言,它是:

"C:\\Users\\salman\\AppData\\Local\\Temp\\Rtmpaskn5E./usarrests.xlsx"

使用矩阵是一样的,你只需要传递你的矩阵而不是USArrests

https://www.statmethods.net/input/exportingdata.html


如何在您的情况下使用它?

A <- setwd("c:/location of the file on this computer")
res<-NULL
for (i in 0:1){
  X <- read.table(A, skip=5, nrow=5)
  M <- as.matrix(X)
  E <- eigen(M)
  res<-rbind(res,E)  # This should aggregate all your Es into a dataframe
}
    class(res)
    print(res) 
    library(xlsx)
    file <- paste(tempdir(), "./eigens.xlsx", sep="")
    res <- write.xlsx(res, file)              # Save E into the file

推荐阅读