【问题标题】:How to make a specific row that begins with a "#" the header in R如何在 R 中创建以“#”开头的特定行
【发布时间】:2016-02-15 07:42:30
【问题描述】:

我正在尝试将 csv 读入 R。我想删除以“#”开头的行之前的行,并将该行作为我的标题。由于以“#”开头的行总是在变化,我不想使用skip =

目前当我做 read.csv("df.csv"):

abc     x      x.1     x.2
def
ghi
#     vbn      crt     ykl
4     rte       77     drf

我想要什么:

#     vbn      crt     ykl
4     rte       77     drf

我试过了:

df <- df[min(grep("vbn",df$x)) :nrow(vnb),]

我知道第二列的标题永远不会改变,并且永远是“vbn”,我认为这会起作用。但这是我的结果。

abc     x      x.1    x.2
#     vbn      crt    ykl
4     rte       77    drf

我也试过了:

library(data.table)
fread("df.csv")

但这不起作用,产生的结果与我刚刚做 read.csv("df.csv") 时的结果相同

任何帮助将不胜感激。如果我需要提供更多信息,请告诉我。谢谢。

【问题讨论】:

    标签: r csv special-characters read.csv


    【解决方案1】:

    这是一个两步的解决方案:我们首先使用 readlines 读取文件并找到以 # 开头的行,然后使用 fread 跳过所有先前的行再次读取。

    # x <- readLines("myfile.csv")
    x <- readLines(textConnection(text))
    
    h <- grep("^#",x) # find the header row
    
    # df <- data.table::fread("myfile.csv",skip=h-1)
    df <- data.table::fread(text,skip=h-1)
    
    # or the base-R alternative (@A.Val's comment)
    # read.table(text = text, skip = h-1, comment.char="", header = T)
    # read.table("myfile.csv", skip = h-1, comment.char="", header = T)
    df
    
    # vbn crt ykl
    1: 4 rte  77 drf
    

    数据

    text <- "abc     x      x.1     x.2
    def
    ghi
    #     vbn      crt     ykl
    4     rte       77     drf"
    

    【讨论】:

    • 您还可以添加一个基本示例:read.table(text = text, skip = h-1, comment.char="", header = T)
    猜你喜欢
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    • 2016-09-28
    • 2018-05-13
    • 2018-08-05
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    相关资源
    最近更新 更多