如何在R中相互减去两个数据帧

时间:2015-01-23 19:35:17

标签: r

我有两个数据帧,我需要每次减去相同的列并将结果存储在不同的数据框中:

dput(t)的

structure(list(time = structure(c(2L, 1L, 3L), .Label = c("1/13/15 1:18 PM", 
"1/13/15 12:18 PM", "1/13/15 2:18 PM"), class = "factor"), web01 = c(24083L, 
24083L, 24083L), web03 = c(24083L, 24083L, 24083L)), .Names = c("time", 
"web01", "web03"), class = "data.frame", row.names = c(NA, -3L
))

dput(d)

structure(list(time = structure(c(2L, 1L, 3L), .Label = c("1/13/15 1:18 PM", 
"1/13/15 12:18 PM", "1/13/15 2:18 PM"), class = "factor"), web01 = c(7764.8335, 
7725, 7711.5), web03 = c(10885.5, 10582.333, 10104.5)), .Names = c("time", 
"web01", "web03"), class = "data.frame", row.names = c(NA, -3L
))

数据帧t和d只是样本,我的实际数据帧有20列。在这种情况下,数据帧t和d具有相同的列名,并且两个数据帧的每一行的时间相同。

我需要在同一时间段内从d中减去d并将结果存储在不同的数据框中。任何想法如何在R

中做到这一点

3 个答案:

答案 0 :(得分:6)

<强>更新

  

rbind_list和rbind_all已被弃用。而是使用bind_rows。

基于评论中的讨论并受到Andrew的回答:

library(dplyr)
df <- bind_rows(d,t) %>% 
  group_by(time = as.POSIXct(time, format="%m/%d/%Y %I:%M %p")) %>%
  summarise_each(funs(diff(.))) %>% 
  data.frame()

这将按时间顺序保留时间,并将结果转换为常规data.frame()

答案 1 :(得分:3)

这是一个data.table方法:

library(data.table)
rbindlist(list(d,t))[, lapply(.SD, diff),
                 by = .(time = as.POSIXct(time, format="%m/%d/%y %I:%M %p"))]

#                  time    web01    web03
#1: 2015-01-13 12:18:00 16318.17 13197.50
#2: 2015-01-13 13:18:00 16358.00 13500.67
#3: 2015-01-13 14:18:00 16371.50 13978.50

编辑:更正的日期格式和输出,已删除.SDcols = ...。

答案 2 :(得分:2)

使用dplyr

newdata<-
  rbind_list(d,t) %>%
  group_by(time) %>%
  summarise_each(funs(diff(.)))



              time    web01    web03
1  1/13/15 1:18 PM 16358.00 13500.67
2 1/13/15 12:18 PM 16318.17 13197.50
3  1/13/15 2:18 PM 16371.50 13978.50