从给定来自另一个数据帧的两个变量的一个数据帧中提取值

时间:2015-04-02 09:19:31

标签: r

我有两个类似于这些的数据框

date = c("2014-07-06", "2014-07-07","2014-07-08") 
temp_0m = c(12, 11, 13) 
temp_1m = c(11, 9, 10) 
temp_2m = c(9, 9, 8) 
temp_3m = c(7, 7, 6) 
foo = data.frame(date, temp_0m, temp_1m, temp_2m, temp_3m)   

DATE = c("2014-07-06", "2014-07-06","2014-07-06","2014-07-07", "2014-07-07","2014-07-07","2014-07-08","2014-07-08","2014-07-08")
TIME = c("01:01:01", "10:02:02", "18:03:03","01:01:01", "10:02:02", "18:03:03","01:01:01", "10:02:02", "18:03:03")
depth = c(1.2, 2.3, 0.4, 1.5, 2.2, 3.4, 2.2, 1.2, 0.5)
bar = data.frame(DATE, TIME, depth)

我想从" foo"中提取值(温度)。给出" bar"的日期和深度。正如你所看到的那样,我在" bar" -data框架中的每个日期都有多个观察点,我希望这些深度观察中的每一个都被赋予来自" foo"的临时值。取决于深度和日期。

我在这个示例数据中寻找的结果如下:

#> NEWbar
#        DATE     TIME depth NEWtemp
#1 2014-07-06 01:01:01   1.2 11
#2 2014-07-06 10:02:02   2.3 9
#3 2014-07-06 18:03:03   0.4 12
#4 2014-07-07 01:01:01   1.5 9
#5 2014-07-07 10:02:02   2.2 9
#6 2014-07-07 18:03:03   3.4 7
#7 2014-07-08 01:01:01   2.2 8
#8 2014-07-08 10:02:02   1.2 10
#9 2014-07-08 18:03:03   0.5 13

我的实际数据框架比这些框架要大得多,因此最少量的手工工作将是一个好主意。

2 个答案:

答案 0 :(得分:1)

在这里,我假设深度'0-1'对应'temp_0m','1-2'对应'temp_1m'等等......我们可以采用ceiling'深度'列合并'foo'和'bar'数据集后(常用列为'date')。如果'temp'列是有序的,那么我们使用ceiling输出作为'column'索引,用1:nrow cbind来根据行/列索引提取'temp'元素。在合并的数据集中创建一个新的“temp”列,并将数据子集化为仅包含“bar”中的列。

d1 <- merge(foo, bar)
d2 <- d1[grep('temp', names(d1))]
d1$temp <- d2[cbind(1:nrow(d2),ceiling(d1$depth))]
d1[c('date', 'depth', 'temp')]
#        date depth temp
#1 2014-07-06   1.2   11
#2 2014-07-07   2.3    9
#3 2014-07-08   0.4   13

更新

基于新数据集

 colnames(foo)[1] <- 'DATE'
 d1 <- merge(foo, bar)
 d2 <- d1[grep('temp', names(d1))]
 d1$temp <- d2[cbind(1:nrow(d2), ceiling(d1$depth))]
 d1[c('DATE', 'TIME', 'depth', 'temp')]
 #        DATE     TIME depth temp
 #1 2014-07-06 01:01:01   1.2   11
 #2 2014-07-06 10:02:02   2.3    9
 #3 2014-07-06 18:03:03   0.4   12
 #4 2014-07-07 01:01:01   1.5    9
 #5 2014-07-07 10:02:02   2.2    9
 #6 2014-07-07 18:03:03   3.4    7
 #7 2014-07-08 01:01:01   2.2    8
 #8 2014-07-08 10:02:02   1.2   10
 #9 2014-07-08 18:03:03   0.5   13

答案 1 :(得分:0)

我认为这应该适合你:

library(dplyr)
dplyr::left_join(x = bar, y = foo)
Joining by: "date"
        date depth temp_0m temp_1m temp_2m temp_3m
1 2014-07-06   1.2      12      11       9       7
2 2014-07-07   2.3      11       9       9       7
3 2014-07-08   0.4      13      10       8       6
相关问题