通过id减去数据帧中的一些数据

时间:2017-01-21 01:10:28

标签: r

与我之前的问题类似但更复杂。

date <- c("2016-03-24","2016-03-24","2016-03-24","2016-03-24","2016-03-24",
          "2016-03-24","2016-03-24","2016-03-24","2016-03-24","2016-03-24")
location <- c(1,1,2,2,3,3,4,4,"out","out")
sensor <- c(1,16,1,16,1,16,1,16,1,16)
Temp <- c(35,34,92,42,21,47,37,42,63,12)
df <- data.frame(date,location,sensor,Temp)

我想减去位置&#34; out&#34;从位置&#34; 4&#34;忽略其他位置,我想通过日期和传感器来做。我尝试了下面的代码,但结果是NAs。我不确定我做错了什么。

DailyMaxInOutDiff04 <- df %>% group_by(date, sensor) %>% summarise(diff = Temp[location=="4"]- Temp[location=="out"])

修改此示例现在正在运行,但它无法使用我的实际数据框。

我想要的结果如下:

        date location sensor diff
1 2016-03-24        4      1  -26
2 2016-03-24        4     16   30

1 个答案:

答案 0 :(得分:1)

在我们进行分组之前,最好先filter

df %>%
    filter(location %in% c(4, 'out')) %>% 
    group_by(date, sensor) %>% 
    summarise(Diff = Temp[location=="4"] - Temp[location=="out"],
              location = first(location)) %>%
    select(1, 2, 4, 3) 
#       date sensor location  Diff
#      <fctr>  <dbl>   <fctr> <dbl>
#1 2016-03-24      1        4   -26
#2 2016-03-24     16        4    30