【发布时间】:2015-11-22 16:53:15
【问题描述】:
我有两个大文件,我正在尝试将 file_1 的第一列中的信息与 file_2 的标题进行匹配。有一个小细节,file_2 的表头开头有一些信息,各列不同,但最后有模式匹配。基本上,我必须在文件 2 的列名称末尾找到来自 file_1 的“模式”,并使用此信息输出 data.frame。
请看下面文件的样子:
**file_1** dim (757*3) the first column of the file_1 contains patterns
10001-101A3 a t
10008-101B6 b g
10235-104A1 c h
- - -
- - -
etc...
**file_2** dim (4120*1079)
blabla.10001.101A3 blbl.2348.101B6 trsdr.1111.111D2 gfder.10008.101B6 ....
12 1223 544 - -
132 23 3564 - -
14 223 33 - -
162 13 344 - -
**Desired output file-3:** I assume that the output size will be 4120*757
blabla.10001.101A3 gfder.10008.101B6 ....
12 - -
132 - -
14 - -
162 - -
我正在尝试使用 R 获取输出(以下是我的脚本),但我也想了解如何在 Unix 中执行此操作(我猜 -awk 和 -grep 可以帮助解决这个问题)。
这是我的 R 脚本:
table1=read.table("file2.tsv.gz", quote=NULL, sep='\t', header=T, fill=T)
table2=read.table("file1.txt", quote=NULL, sep='\t', header=T, fill=T)
# dim(table1 4120 * 1079) -> need to reduce amount of columns to 757
# dim(table2 757 * 3)
###### the header in table1 has following view 10001.101A3, thus we need to substitute '-' to '.' in pattern
### What to do:
### 1) Use gsub() function to substitute '-' by '.'
### 2) Use gsub() function to remove space in the end of string ' ' by ''
### 3) Find modified pattern in the end of column's name
### 4) Apply to the entire table
pattern=table2[,1] # '10001-101A3 ' '10008-101B6 '
for (x in pattern) {
ptn=gsub('-','.',x)
ptn1=gsub(' ','',ptn) # pattern to be matched'
# '10001.101A3' '10008.101B6'
find_match=table1[,(grepl('^.+ptn1$', header))]
final_tb=table1[,find_match]
}
我认为问题在于 grepl() 函数中 ptn1 的数据表示,因为当我插入 10001.101A3 而不是 ptn1 时,我得到了一次运行的答案,但显然我需要遍历它。
我也试过get(ptn1),但还是不行。
我会很感激您的 cmets 以及如何在 Unix 中执行此操作的任何想法(我是 Unix 的非常基本的用户,因此目前无法执行此任务)。
######################## 跟踪小数据df=data.frame(aa24.12a,dda43.23s,fds24.12a,sdf24.112f)
z=c('24-12a ','43-23s ') # 模式
aa24.12a fds24.12a aa24.12a.1 fds24.12a.1
1 2 34 2 34
2 3 2 3 2
3 4 1 4 1
4 56 3 56 3
5 3 5 3 5
header=colnames(df)
for (x in z){
ptn=gsub('-','.',x)
ptn1=gsub(' ','',ptn)# correct pattern
find_match=grep('^.+24.12a$', header)# find match of pattern in header
tbl=df[,find_match]
}
> tbl
aa24.12a fds24.12a
1 2 34
2 3 2
3 4 1
4 56 3
5 3 5
谢谢
【问题讨论】: