将连续的文本文件读入 data.frame

Read in a continuous text file into data.frame

我有一个只有一栏的文本文件。就像:

sample1

color 12
length 34
validity 90



sample2

color 15
length 20
validity 120



sample3

color 34
validity 79

样本之间有3行,样本id和它的属性之间有1行。另外,对于 sample3,缺少长度记录。

我想将此文件读入 R data.frame,使其看起来像:

       sample1   sample2   sample3
color    12        15        34
length   34        20        NA
validity 90        120       79

您遇到了数据清理问题。这是我为您提供的解决方案。

我将您的 "TXT" 文件复制并粘贴到 Mac 上的空白 TextEdit 文档中,并将其另存为 file.txt。需要您的 "TXT" 文件中显示的顺序:

data <- unlist(read.table("file.txt", header=F, sep="\t", stringsAsFactors=F), use.names=F)
data

sample_names <- data[grep("sample", data), drop=T]
sample_names 
## [1] "sample1" "sample2" "sample3"

color <- data[grep("color", data), drop=T]
color
## "color 12" "color 15" "color 34"

length <- data[grep("length", data), drop=T]
length #note missing term, and requires manual coding
## [1] "length 34" "length 20"

length <- c(length, NA)
length
## [1] "length 34" "length 20" NA   

validity <- data[grep("validity", data), drop=T]
validity
## [1] "validity 90"  "validity 120" "validity 79" 

## Assemble into data.frame:
assembled_df <- rbind(color, length, validity)
colnames(assembled_df) <- sample_names #update column names
assembled_df
##          sample1       sample2        sample3      
## color    "color 12"    "color 15"     "color 34"   
## length   "length 34"   "length 20"    NA           
## validity "validity 90" "validity 120" "validity 79"

请注意,代码可能无法推广。这取决于实际的 TXT 文件的外观。重要的是要学会 1) 了解您的数据(您所做的),2) 提出策略,3) 然后是解决方案。