【问题标题】:Reading table from a crude text file in R从 R 中的原始文本文件中读取表格
【发布时间】:2012-03-28 21:27:45
【问题描述】:

我有一个不需要前几行的文本文件,然后有一个像这样的表格

-连字符-
| col1 | col2 | col3 col4 col5 |
-连字符-
| 1 | 2012 年 3 月 22 日下午 2:24:21 | 0 0 1 |
| 2 | 2012 年 3 月 22 日下午 2:24:21 | 1 · 0 |

  1. Col1、Col2 由 | 分隔但是 col3,col4 和 col5 只是用空格隔开。
  2. 数据类型应保持为 col2 日期和 col3,4,5 为数字?
  3. 第 2 行,Col4 是点,因此应该读取广告 NA
  4. 连字符行以 - - - 开头和结尾

问题:
1.我可以使用scan,但是如何避免读取“|”和“-”?
2. 我可以跳过前几行,但除了前几行之外,如何跳过第 50 行。

【问题讨论】:

    标签: r text import


    【解决方案1】:

    您可以按原样将其读取为表格,然后拆分列并重新组合。

    txt <- "| col1 | col2 | col3 col4 col5 |
    | 1 | 2:24:21 PM 3/22/2012 | 0 0 1 |
    | 2 | 2:24:21 PM 3/22/2012 | 1 · 0 |"
    
    x <- read.table(text = txt, sep = "|", header = TRUE, stringsAsFactors = FALSE)
    
    ## drop unnecessary columns from the original sep split
    x <- x[,-c(1,ncol(x))]
    
    ## split the desired column by the spaces, result is a character matrix
    ## including an unnecessary first column
    split.col3 <- do.call("rbind", strsplit(x[,3], " "))
    
    ## bind to the original, dropping the unneeded columns
    cbind(x[,-3], split.col3[,-1])
      col1                   col2 1 2 3
    1    1  2:24:21 PM 3/22/2012  0 0 1
    2    2  2:24:21 PM 3/22/2012  1 · 0
    

    我避免提及原始列名,因为您说过要跳过这些行。只需将header = FALSEskip = 50 添加到read.table 调用,然后添加任何有意义的列名。

    此外,您还可以去掉“.”。根据需要从列中转换为日期时间格式或数字。如果您事先知道它们,请在 read.table 中使用colClasses。对我来说,将其分解为多个步骤是有意义的,而不是尝试使用一个读取功能来完成所有操作。

    【讨论】:

    • ...和read.table 中的comment.char="-" 应该跳过数据中的任何其他连字符行。
    【解决方案2】:

    这可以分三个步骤完成。 (1) 使用"|" 作为分隔符读入文件,(2) 创建一个只有三列(包含为一列)的新文件,(3) 然后使用空格分隔符将它们读回。以下代码应该可以帮助您了解大部分情况。可能需要进行的更改:文件名、V4 列名以及导航到正确的目录 (getwd/setwd)。

    a <- read.delim("a.txt", FALSE, sep="|")
    write.table(a$V4, file="b.txt", quote=FALSE, row.names=FALSE, col.names=FALSE)
    b <- read.delim("b.txt", FALSE, sep=" ")
    

    合并ab的相应列即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 2022-12-16
      • 2020-07-20
      相关资源
      最近更新 更多