如何按键/值交错两个数据帧中的行?

时间:2018-07-18 17:02:28

标签: r

我想通过基于时间戳的交错将两个表中的数据合并在一起。由于“框”列具有多个值,因此它们的长度不相等。

DateTime    Box TempIn
10/10/2017 4:00 B1  5
10/10/2017 4:00 B2  5
10/10/2017 4:00 B3  5
10/10/2017 5:00 B1  5
10/10/2017 5:00 B2  5
10/10/2017 5:00 B3  5

DateTime    TempOut
10/10/2017 4:00 22
10/10/2017 5:00 22

我的目标是插入“ Temp *”列,以便最终表如下所示:

DateTime    Box Temp
10/10/2017 4:00 B1  5
10/10/2017 4:00 B2  5
10/10/2017 4:00 B3  5
10/10/2017 4:00 Ext 22
10/10/2017 5:00 B1  5
10/10/2017 5:00 B2  5
10/10/2017 5:00 B3  5
10/10/2017 5:00 Ext 22

有什么建议吗?使用TidyR,我可以做到这一点,但是我的日期却乱了。

spread(df, Box, TempIn)

         DateTime B1 B2 B3
1 10/10/2017 4:00  5  5  5
2 10/10/2017 5:00  5  5  5

df$Ext <- df2$TempOut

         DateTime B1 B2 B3 Ext
1 10/10/2017 4:00  5  5  5  22
2 10/10/2017 5:00  5  5  5  22


df %>% gather(Box, Temp, -DateTime)
         DateTime Box Temp
1 10/10/2017 4:00  B1    5
2 10/10/2017 5:00  B1    5
3 10/10/2017 4:00  B2    5
4 10/10/2017 5:00  B2    5
5 10/10/2017 4:00  B3    5
6 10/10/2017 5:00  B3    5
7 10/10/2017 4:00 Ext   22
8 10/10/2017 5:00 Ext   22

1 个答案:

答案 0 :(得分:0)

我假设较大的数据帧称为df,而另一个称为df2

# Rename to prepare for rbind
names(df) <- ifelse(names(df) == 'TempIn', 'Temp', names(df))
names(df2) <- ifelse(names(df2) == 'TempOut', 'Temp', names(df))
# Add box to df2
df2$Box <- 'Ext'

# Split each by DateTime, rbind each of the splits, then rbind everything
do.call(rbind, Map(rbind, split(df, df$DateTime), split(df2, df2$DateTime)))

#           DateTime Box Temp
# 1: 10/10/2017 4:00  B1    5
# 2: 10/10/2017 4:00  B2    5
# 3: 10/10/2017 4:00  B3    5
# 4: 10/10/2017 4:00 Ext   22
# 5: 10/10/2017 5:00  B1    5
# 6: 10/10/2017 5:00  B2    5
# 7: 10/10/2017 5:00  B3    5
# 8: 10/10/2017 5:00 Ext   22

这些都给出相同的结果

do.call(rbind, rbind(split(df, df$DateTime), split(df2, df2$DateTime)))

##################################

library(tidyverse)

list(df, df2) %>% 
  map(~split(.x, .x$DateTime)) %>% 
  do.call(what = rbind) %>% 
  do.call(what = rbind)

##################################

list(df, df2) %>% 
  map(~split(.x, .x$DateTime)) %>%
  flatten %>% 
  .[order(names(.))] %>% 
  bind_rows