【问题标题】:In R, how to read file with custom end of line (eol)在 R 中,如何使用自定义行尾 (eol) 读取文件
【发布时间】:2015-04-22 16:04:14
【问题描述】:

我有一个要在 R 中读取的文本文件(并存储在 data.frame 中)。该文件按多行和多列组织。 “sep”和“eol”都是自定义的。

问题:无法在 read.table(...) (或 read.csv(...)、read.csv2(.. .),...) 也不在 fread(...) 中,我找不到解决方案。

我在这里进行了搜索(“[r] read eol”和其他我不记得了),但我没有找到解决方案:唯一的方法是预处理更改 eol 的文件(在我的情况下不可能因为在某些字段中,我可以找到类似 \n、\r、\n\r、"、... 这就是自定义的原因。

谢谢!

【问题讨论】:

  • 如果您不愿意使用外部实用程序修改它,我怀疑您需要将其作为二进制文件读取。

标签: r read.table eol


【解决方案1】:

您可以通过两种不同的方式来处理:

A.如果文件不太宽,您可以使用scan 读取所需的行,并使用strsplit 将其拆分为所需的列,然后组合成data.frame。示例:

# Provide reproducible example of the file ("raw.txt" here) you are starting with
your_text <- "a~b~c!1~2~meh!4~5~wow"
write(your_text,"raw.txt"); rm(your_text)  

eol_str = "!" # whatever character(s) the rows divide on
sep_str = "~" # whatever character(s) the columns divide on

# read and parse the text file   
# scan gives you an array of row strings (one string per row)
# sapply strsplit gives you a list of row arrays (as many elements per row as columns)
f <- file("raw.txt")
row_list <- sapply(scan("raw.txt", what=character(), sep=eol_str), 
                   strsplit, split=sep_str) 
close(f)

df <- data.frame(do.call(rbind,row_list[2:length(row_list)]))
row.names(df) <- NULL
names(df) <- row_list[[1]]

df
#   a b   c
# 1 1 2 meh
# 2 4 5 wow

B.如果 A 不起作用,我同意 @BondedDust 的观点,即您可能需要一个外部实用程序——但您可以在 R 中使用 system() 调用它并执行查找/替换以将您的文件重新格式化为 read.table。您的调用将特定于您的操作系统。示例:https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands。由于您注意到您的文本中已经有\n\r\n,我建议您首先找到并用临时占位符替换它们——也许是它们自己的引用版本——然后你可以在你有之后将它们转换回来建立你的data.frame

【讨论】:

    猜你喜欢
    • 2021-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多