在 r 中创建矩阵时出错

发布于 2024-11-27 08:00:16 字数 715 浏览 0 评论 0原文

我正在尝试在 R 中创建一个 256*256 矩阵。我认为这是一个简单的任务...如果我创建数据以便

aa=1:65536
z = matrix(bb,nrow=256,ncol=256,byrow=T)

我拥有我想要的矩阵,例如

     [,1] [,2] [,3] [,4] [,5] 
[1,]    1    2    3    4    5 

等等。但是,我不是创建“aa”数据,而是读取它,这样

aa = read.table("myfile.txt",header=F)
> aa[c(1:10),]
[1] 1513.708 1513.971 1514.067 1513.971 1513.875 1513.622 1513.524 1513.578 1513.577 1513.481

当我读取 aa 时,数据看起来不错,但当我尝试将其转换为矩阵时,矩阵读取为

     [,1]          [,2]          [,3]          [,4]          [,5] 
[1,] Numeric,65536 Numeric,65536 Numeric,65536 Numeric,65536 Numeric,65536 

等等。知道为什么会发生这种情况吗?

非常感谢您的帮助!

I am trying to create a 256*256 matrix in R. Simple task I thought... If I create the data such that

aa=1:65536
z = matrix(bb,nrow=256,ncol=256,byrow=T)

I have the matrix I want e.g.

     [,1] [,2] [,3] [,4] [,5] 
[1,]    1    2    3    4    5 

and so on. However, I am not creating the "aa" data but reading it instead such that

aa = read.table("myfile.txt",header=F)
> aa[c(1:10),]
[1] 1513.708 1513.971 1514.067 1513.971 1513.875 1513.622 1513.524 1513.578 1513.577 1513.481

When I read aa, the data looks fine but when I try and turn it into a matrix, the matrix reads as

     [,1]          [,2]          [,3]          [,4]          [,5] 
[1,] Numeric,65536 Numeric,65536 Numeric,65536 Numeric,65536 Numeric,65536 

and so on. Any idea why this is happening?

Thank you very much for your help!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜访吸血鬼 2024-12-04 08:00:16

请注意 ?read.table 的“内存使用”部分中的这一段:

 ‘read.table’ is not the right tool for reading large matrices,
 especially those with many columns: it is designed to read _data
 frames_ which may have columns of very different classes.  Use
 ‘scan’ instead for matrices.

当然,您的 256x265 矩阵并不,但 scan 仍然看起来更合适。

aa <- matrix(scan("myfile.txt"), nrow=256, ncol=256, byrow=TRUE)

Note this paragraph in the 'Memory usage' section of ?read.table:

 ‘read.table’ is not the right tool for reading large matrices,
 especially those with many columns: it is designed to read _data
 frames_ which may have columns of very different classes.  Use
 ‘scan’ instead for matrices.

Granted, your 256x265 matrix isn't large but scan still seems more appropriate.

aa <- matrix(scan("myfile.txt"), nrow=256, ncol=256, byrow=TRUE)
美人如玉 2024-12-04 08:00:16

尝试将 sep="" 参数传递给 read.table()。使用 sep 参数,您可以定义文件的分隔符,您可以定义哪些分隔符以及如何在 ?read.file 中找到分隔符。如果还有其他问题请评论。

编辑:您可以复制粘贴一些您正在阅读的文件吗?

Try the sep="" parameter to read.table(). With the sep-parameter you can define the separators for your file, which separators you can define and how you find in ?read.file. Comment if there are any additional problems.

EDIT: can you copy-paste us a little of the file you are reading?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文