我有 dataframe1 和一个行索引向量:
dataframe1 <-data.frame(time = c(0.5, 1.5, 2.5, 3.5, 4.5, 5),
x = c("light", "light", "light", "dark", "dark", "dark"))
vector <- c(1, 3, 6)
我也有 dataframe2
dataframe2 <- data.frame(time = c(0.6, 1, 1.4, 2, 2.4, 3.2, 3.5, 4, 4.5, 5))
我想使用 dataframe1$time
中与 vector
中的行位置相对应的值来定义 dataframe2
中的边界,这样我最终会得到这个数据集:
dataframe2
time x
1 0.6 light
2 1.0 light
3 1.4 light
4 2.0 light
5 2.4 light
6 3.2 dark
7 3.5 dark
8 4.0 dark
9 4.5 dark
10 5.0 dark
换句话说,我想使用由 vector
(例如,1 & 3)和相应的 dataframe1$time
(例如,0.5 & 2.5)给出的行索引来查找 {{1 }} 即 >= 0.5 和 =< 2.5(例如,0.6, 1, 1.4, 2, 2.4),然后在 dataframe2$time
中创建一个新列 x
对应于 dataframe2
.
我不想想要使用 dataframe1$x
作为键值(例如 cbind)组合数据集。
我希望这很清楚。预先感谢您的帮助。
答案 0 :(得分:2)
dataframe2$x<-with(dataframe1, unique(x)[findInterval(dataframe2$time, time[vector],all.inside = TRUE)])
dataframe2
time x
1 0.6 light
2 1.0 light
3 1.4 light
4 2.0 light
5 2.4 light
6 3.2 dark
7 3.5 dark
8 4.0 dark
9 4.5 dark
10 5.0 dark
答案 1 :(得分:1)
我们可以使用滚动连接
library(data.table)
setDT(dataframe1[vector,])[dataframe2, on = .(time = time), roll = -Inf]
-输出
time x
1: 0.6 light
2: 1.0 light
3: 1.4 light
4: 2.0 light
5: 2.4 light
6: 3.2 dark
7: 3.5 dark
8: 4.0 dark
9: 4.5 dark
10: 5.0 dark