如何在 R 中创建以“#”开头的特定行 header
How to make a specific row that begins with a "#" the header in R
我正在尝试将 csv 读入 R。我想删除以“#”开头的行之前的行,并将该行设为我的 header。由于以“#”开头的行总是在变化,我不想使用 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")
如有任何帮助,我们将不胜感激。如果我需要提供更多信息,请告诉我。谢谢。
这里有一个两步解决方案:我们首先用 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"
我正在尝试将 csv 读入 R。我想删除以“#”开头的行之前的行,并将该行设为我的 header。由于以“#”开头的行总是在变化,我不想使用 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")
如有任何帮助,我们将不胜感激。如果我需要提供更多信息,请告诉我。谢谢。
这里有一个两步解决方案:我们首先用 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"