我有两个数据框。
df1
包含三列,例如。
location start_position end_position
a_a1 2500 5500
b_a1 5600 6500
c_a1 7500 8900
而
df2
包含以下列
Sample Position
A1 2300
A2 5300
A3 7600
我想要的只是我想要 df2 中的第三列,说明来自
df1
的位置,如 df1
中所示。如果 df2$Position
值位于 df1$start_position
和 df1$end_position
之间,如下所示
Sample Position Location
A1 2300 a_a1
A2 5300 b_a1
A3 7600 c_a1
一种低效的方法是创建一个向量作为索引。
pos_index <- vector()
for (i in seq_len(nrow(df1))) {
pos_index[df1$start_position[i]:df1$end_position[i]] <- df1$location[i]
}
df2$Location <- pos_index[df2$Position]
df2
Sample Position Location
1 A1 2300 <NA>
2 A2 5300 a_a1
3 A3 7600 c_a1
A1 不适用,因为 2300 不在任何位置。您能再检查一下您的示例吗?