【发布时间】:2020-04-25 15:39:33
【问题描述】:
我想导入一个文本文件,其中包含一个结果表,上面有两个“标题”文本行。标题行的内容需要作为额外的列包含在结果 data.frame 中。
在以下示例文本文件中,Region 和 Month 行是标题行,文件的其余部分是结果表。
Region South Africa
Month July
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
需要成为一个包含区域和月份列的data.frame:
wanted.df<-structure(list(Sepal.Length = c(1, 2, 3), Sepal.Width = c(5.1,
4.9, 4.7), Petal.Length = c(3.5, 3, 3.2), Petal.Width = c(1.4,
1.4, 1.3), Species = c(0.2, 0.2, 0.2), Region = c("South Africa",
"South Africa", "South Africa"), Month = c("July", "July", "July"
)), row.names = c(NA, -3L), class = c("spec_tbl_df", "tbl_df",
"tbl", "data.frame"))
我设法通过创建两个 data.frames 来做到这一点,一个包含标题信息,第二个包含结果表,然后合并它们,但这在我看来有点笨拙:
#Create data frame from first two lines of text (the header)
header <- scan('example.txt', nlines = 2, what = character(),sep = "\n")
header.df<-data.frame((sapply(header,function(x){str_split(x, "\t")})),stringsAsFactors=FALSE)
colnames(header.df) <- as.character(header.df[1,])
header.df<-header.df[-1,]
#Create data frame from first remainder of the file which contains the results table
results.df<-read_tsv('example.txt',col_names = T,skip=2)
#helper column added to both data frames for merging
results.df$helper.col<- "match"
header.df$helper.col<-"match"
df.example<-inner_join(results.df,header.df, by = "helper.col", copy = FALSE)
wanted.df<-select(df.example,-helper.col)
有没有更优雅的方式?
【问题讨论】:
-
你怎么知道“南非”是一个词而不是单独的词?还是您知道标题中总是只有两列?
-
@RonakShah - 它似乎是一个制表符分隔文件(OP 使用
read_tsv()并在\t上拆分标题信息)。 -
@RonakShah,是的,它是一个制表符分隔文件(并且标题中的列数是固定的)。