【问题标题】:How to make read.table() ignore rows with error如何使 read.table() 忽略错误行
【发布时间】:2014-05-22 18:04:49
【问题描述】:

我必须用read.table 读取一个csv 文件,但我有一个小问题:我的csv 包含一些这样的行:

  A  B  C
1 2  3  4
2 2  5  6
3 4  8  error:8
. .  .  .
. .  .  .
. .  .  .

我想删除我的 csv 文件中包含错误的所有行或删除错误并让这些行,我不知道 R 是否可能? 这是我的代码:

file <- paste("C:\\test.csv")
table <- read.table(file,sep=",",header=T,fill=TRUE)

【问题讨论】:

标签: r csv dataframe row


【解决方案1】:

这应该可行:

dat.file <- paste("C:\\test.csv")

# use readLines() to get file line-by-line 
dat.in <- readLines(dat.file)

# filter out "error"
dat.in <- dat.in[grep("error", dat.in, invert=TRUE)]

# turn structure into a string we can pass to textConnection
read.csv(textConnection(paste(dat.in, collapse="\n")), header=TRUE)

如果您使用的是 Linux/OS X 系统,我会让您将文件通过系统grep 进行管道传输,但是,唉,#Windows。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-02
    • 2014-04-09
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    相关资源
    最近更新 更多