在R中的对象之间添加列

时间:2013-11-13 14:55:34

标签: r

文件1:

pos qual    

15 bad    
1 good
18 bad
19 good
2 bad
3 bad
4 good
16 bad
17 ugly

file2的:

start stop region
1 10 heaven
11 15 hell
16 20 seaLevel

我该如何创建:

pos qual region    
1 good heaven
2 bad heaven
3 bad heaven
4 good heaven
15 bad hell
16 bad seaLevel
17 ugly seaLevel
18 bad seaLevel
19 good seaLevel

我有一段时间没用过R所以它全都消失了!对学习忘记的时间感到沮丧。

我想到了这一点,但缺少一些东西,我虚弱地回想起有一条捷径:

for(i in 1:nrow(file1...
    for j in 1:nrow(file2...
        if(file1[i]$pos>file2[j]$start & file1[i]$pos<file2[j]$stop){
            file1[i]$region=file2[j]$region
}

1 个答案:

答案 0 :(得分:0)

您可以使用data.table进行滚动连接:

df1 <- read.table(text="pos qual    
1 good
2 bad
3 bad
4 good
15 bad
16 bad
17 ugly
18 bad
19 good", header=TRUE)

df2 <- read.table(text="start stop region
1 10 heaven
11 20 hell", header=TRUE)

library(data.table)
DT1 <- data.table(df1, key="pos")
DT2 <- data.table(df2, key="start")
DT2[DT1, roll=T]

#    start stop region qual
# 1:     1   10 heaven good
# 2:     2   10 heaven  bad
# 3:     3   10 heaven  bad
# 4:     4   10 heaven good
# 5:    15   20   hell  bad
# 6:    16   20   hell  bad
# 7:    17   20   hell ugly
# 8:    18   20   hell  bad
# 9:    19   20   hell good