从R中的文件中读取



我试图在r中读取文本头文件,除了以下内容外,我一直很成功:

文件的一部分包含:

.  
.    
. (Other stuff)  
spectra names = {  
 Endmember  1, Endmember  2, Endmember  3, Endmember  4, Endmember  5,   
 Endmember  6, Endmember  7, Endmember  8, Endmember  9, Endmember  10,   
 Endmember  11, Endmember  12, Endmember  13, Endmember  14, Endmember  15,   
 Endmember  16, Endmember  17, Endmember  18, Endmember  19, Endmember  20,   
 Endmember  21, Endmember  22, Endmember  23, Endmember  24, Endmember  25,   
 Endmember  26, Endmember  27, Endmember  28, Endmember  29, Endmember  30}  
.  
.  
.

我希望输出是一个包含光谱名称的列表,即["Endmember 1" "Endmember 2"等…

我尝试了read.csv(), read.table(),但似乎没有工作。我被行尾和'{','}'字符难住了

我想做的是:开始读取"光谱名称",然后将{}之间的所有内容存储为上面提到的字符串数组。

这是如何实现Justin建议的一个示例。假设数据文件如下所示:

4 5 6
2 3 4
1 2 3 
spectra names = {Endmember  1, Endmember  2, Endmember  3}
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2

你可以这样读:

aa <- readLines('c:/users/Mark W Miller/simple R programs/odd data file with headers in the middle.txt', 
     n = 4)
bb <- gsub("spectra names = {","", aa[4], fixed=TRUE)
bb <- gsub("}","", bb, fixed=TRUE)
bb <- gsub("  "," ", bb, fixed=TRUE)
bb <- gsub(", ",",", bb, fixed=TRUE)
cc <- unlist(strsplit(bb, ","))
cc
dd <- read.table('c:/users/Mark W Miller/simple R programs/odd data file with headers in the middle.txt', 
     skip = 4, header=F)
dd
colnames(dd) <- cc
dd

我确信有办法把我所有的gsub语句浓缩成一行。如果这不是你想要的,也许你可以把它作为一个开始。

我不确定我是否理解创建列名列表的部分。

使用评论中建议的scan和gsub,你可以很容易地得到这个

tt <- scan(text = "spectra names = {  
  Endmember  1, Endmember  2, Endmember  3, Endmember  4, Endmember  5,   
  Endmember  6, Endmember  7, Endmember  8, Endmember  9, Endmember  10,   
  Endmember  11, Endmember  12, Endmember  13, Endmember  14, Endmember  15,   
  Endmember  16, Endmember  17, Endmember  18, Endmember  19, Endmember  20,   
  Endmember  21, Endmember  22, Endmember  23, Endmember  24, Endmember  25,   
  Endmember  26, Endmember  27, Endmember  28, Endmember  29, Endmember  30}" ,what = 'character' ,sep =',')
gsub('[{|}]','',tt) ## not really clever but it is a good begining
[1] "spectra names =   " "  Endmember  1"     " Endmember  2"      " Endmember  3"      " Endmember  4"      " Endmember  5"     
[7] "   "                "  Endmember  6"     " Endmember  7"      " Endmember  8"      " Endmember  9"      " Endmember  10"    
[13] "   "                "  Endmember  11"    " Endmember  12"     " Endmember  13"     " Endmember  14"     " Endmember  15"    
[19] "   "                "  Endmember  16"    " Endmember  17"     " Endmember  18"     " Endmember  19"     " Endmember  20"    
[25] "   "                "  Endmember  21"    " Endmember  22"     " Endmember  23"     " Endmember  24"     " Endmember  25"    
[31] "   "                "  Endmember  26"    " Endmember  27"     " Endmember  28"     " Endmember  29"     " Endmember  30"   

相关内容

  • 没有找到相关文章

最新更新