[英]Put the first row as the column names of my dataframe with dplyr in R
[英]R- my first row has # character in the column names?
這里有幾種可能性:
1)處理兩次使用readLines
將其作為行L
的字符向量讀入。 然后刪除#並使用read.table
讀取L
:
L <- sub("#", "", readLines("myfile.dat"))
read.table(text = L, header = TRUE)
2)分別讀取標頭對於較小的文件,以前的方法比較短,應該可以,但是如果文件較大,則可能不希望對其進行兩次處理。 在這種情況下,請使用readLines
僅讀入標題行,對其進行修復,然后再應用列名讀取其余部分。
File <- "myfile.dat"
col.names <- scan(text = readLines(File, 1), what = "", quiet = TRUE)[-1]
read.table(File, col.names = col.names)
3)管道另一種方法是利用外部命令:
File <- "myfile.dat"
cmd <- paste("sed -e 1s/.//", File)
read.table(pipe(cmd), header = TRUE)
在類似UNIX的系統上, sed
應該可用。 在Windows上,您將需要安裝Rtools並確保sed
位於PATH
上,或者使用文件的路徑:
cmd <- paste("C:/Rtools/bin/sed -e 1s/.//", File)
read.table(pipe(cmd), header = TRUE)
一種方法是只對第一行進行一次單獨的讀取,以嗅出列名。 然后,像以前一樣做一個read.table
,並跳過第一行。
f <- "path/to/yourfile.csv"
con <- file(f, "r")
header <- readLines(con, n=1)
close(con)
df <- read.table(f, header=FALSE, sep = " ", skip=1) # skip the first line
names(df) <- strsplit(header, "\\s+")[[1]][-1] # assign column names
但是,我不喜歡這種方法,而是希望您修復平面文件的源, 以免包含麻煩的#
符號。 另外,如果您只需要一次性完成此要求,則還可以手動編輯平面文件以刪除#
符號。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.