在R中读取ascii文件

标签 r header read.table

我正在尝试使用 read.table 在 R 中读取文件 (ascii) 该文件如下所示:

  DAILY MAXIMUM TEMPARATURE  
  YEAR DAY MT DT   LAT. 66.5   67.5   68.5   69.5   70.5
  1969 001 01 01   6.5  99.90  99.90  31.90  99.90  99.90 
  1969 001 01 01   7.5  99.90  20.90  99.90  99.90  23.90
  1969 001 01 01   8.5  99.90  99.90  30.90  99.90  18.90
  .....
  ..... 
  YEAR DAY MT DT   LAT. 66.5   67.5   68.5   69.5   70.5
  1969 001 01 02   6.5  21.90  99.90  99.90  99.90  99.90 
  1969 001 01 02   7.5  99.90  33.90  99.90  99.90  99.90
  1969 001 01 02   8.5  99.90  99.90  15.90  99.90  99.90
  .....
  .....
  YEAR DAY MT DT   LAT. 66.5   67.5   68.5   69.5   70.5
  1969 001 01 03   6.5  99.90  99.90  99.90  99.90  99.90 
  1969 001 01 03   7.5  99.90  99.90  99.90  99.90  99.90
  1969 001 01 03   8.5  99.90  99.90  99.90  99.90  99.90
  .....
  .....

我阅读它使用:

inp=read.table("MAXT1969.TXT",skip=1,header=T)

文件已被读取,内容在变量inp中。

我有两个问题-

我。查看前 5 列的命令提供了一些额外的信息以及所需的输出, 例如,inp[1,5] 给出以下输出:

> inp[1,5]
  "[1] 6.5
  33 Levels: 10.5 11.5 12.5 13.5 14.5 15.5 16.5 17.5 18.5 19.5 20.5 21.5 ... LAT."

我不想要额外的信息,只想要值(value)。我哪里错了?

二。在每 32 行之后,我有一个标题(YEAR DAY ....)。如何忽略定期阅读标题?

最佳答案

试试 comment.char="Y",这将使 read.table 忽略所有以 Y 开头的行。 stringsAsFactors=FALSE 将避免将字符串转换为因子。

inp <- read.table("MAXT1969.TXT", skip = 1, header=FALSE, comment.char="Y", stringsAsFactors=FALSE )

#Read just first row to get header names
cols <- read.table("MAXT1969.TXT", header=FALSE, skip=1, nrows=1  )
names(inp) <- cols  

inp
##   YEAR DAY MT DT LAT. 66.5 67.5 68.5 69.5 70.5
## 1 1969   1  1  1  6.5 99.9 99.9 31.9 99.9 99.9
## 2 1969   1  1  1  7.5 99.9 20.9 99.9 99.9 23.9
## 3 1969   1  1  1  8.5 99.9 99.9 30.9 99.9 18.9
## 4 1969   1  1  2  6.5 21.9 99.9 99.9 99.9 99.9
## 5 1969   1  1  2  7.5 99.9 33.9 99.9 99.9 99.9
## 6 1969   1  1  2  8.5 99.9 99.9 15.9 99.9 99.9
## 7 1969   1  1  3  6.5 99.9 99.9 99.9 99.9 99.9
## 8 1969   1  1  3  7.5 99.9 99.9 99.9 99.9 99.9
## 9 1969   1  1  3  8.5 99.9 99.9 99.9 99.9 99.9

#Since the stringsAsFactor = FALSE was used numbers were read correctly. 
inp[1, 5]
## [1] 6.5

关于在R中读取ascii文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15919832/

相关文章:

r - 使用 R 在一张图中绘制光谱数据

r - 如何避免 uisng rbind 和 data.frame 的重复值?

r - geom_rect + coord_map = 非常慢

c++ - 多重定义错误 : How to declare a reference in a header file?

r - 如何跳过 R 中 read.table() 中的空白文件

r - 将点平均在一起而不重复并减少最终数据帧

c# - 从 C# 中的 .docx 文件的页眉和页脚获取图像

C++在类中使用函数时出错

r - 防止 fread() 中的列类推断

r - 使用 colClasses 时 read.table 出错