【问题标题】:Skip specific rows using read.csv in R [duplicate]在 R [重复] 中使用 read.csv 跳过特定行
【发布时间】:2016-12-30 20:20:58
【问题描述】:

在将文件导入 R 中的数据框时,我希望跳过 csv 文件的第一行和第三行。

在原始文件中,我的标题位于第 2 行。

使用 read.csv 中的 skip 参数,我可以跳过第一行并将 header 参数设置为 TRUE,因为我的数据框中仍然有原始文件的第 3 行。

谁能建议如何跳过 R 中的多个特定行,下面是我能够拼凑的内容?

我可以将向量传递给指定要忽略的确切行的跳过参数吗?

prach <- read.csv("RSRAN104_-_PRACH_Propagation_Delay-PLMN-day-rsran_RU50EP1_reports_RSRAN104_xml-2016_08_23-21_33_03__604.csv", header = TRUE, sep = ",", stringsAsFactors = FALSE, skip = 1)

【问题讨论】:

  • 我很想看看其他人怎么说,但如果第 1 行和第 3 行不为空,您可能需要跳过所有 3 行并手动管理您的标题名称。
  • 如果您不介意手动修改文件,您可以将comment character# 一样添加到第三行,然后执行:read.csv(file, skip = 1, header = T, comment.char = "#")
  • 为什么不跳过第一行,从第2行开始读取csv(包括标题),在read.csv()之后删除第三行?

标签: r read.csv


【解决方案1】:

一种方法是使用两个read.csv 命令,第一个读取标题,第二个读取数据:

headers = read.csv(file, skip = 1, header = F, nrows = 1, as.is = T)
df = read.csv(file, skip = 3, header = F)
colnames(df)= headers

我创建了以下文本文件来测试:

do not read
a,b,c
previous line are headers
1,2,3
4,5,6

结果是:

> df
  a b c
1 1 2 3
2 4 5 6

【讨论】:

    【解决方案2】:

    我的完美解决方案:

    #' read csv table, wrapper of \code{\link{read.csv}}
    #' @description read csv table, wrapper of \code{\link{read.csv}}
    #' @param tolower whether to convert all column names to lower case
    #' @param skip.rows rows to skip (1 based) before read in, eg 1:3
    #' @return returns a data frame
    #' @export
    ez.read = function(file, ..., skip.rows=NULL, tolower=FALSE){
        if (!is.null(skip.rows)) {
            tmp = readLines(file)
            tmp = tmp[-(skip.rows)]
            tmpFile = tempfile()
            on.exit(unlink(tmpFile))
            writeLines(tmp,tmpFile)
            file = tmpFile
        }
        result = read.csv(file, ...)
        if (tolower) names(result) = tolower(names(result))
        return(result)
    }
    

    【讨论】:

    • 这为我解决了一个棘手的问题,即我需要跳过文件底部带有元数据的 ascii 文件,以及需要跳过的标题。我喜欢在使用该函数时也可以将命令传递给 read.csv。我用过: test
    • 我很高兴它有帮助!
    猜你喜欢
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    相关资源
    最近更新 更多