2017-01-22 11 views
0

もう一度前の2つの質問が続きますが、少し異なる問題です。データの欠落したdplyrを使用

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") 
location <- c(1,1,2,2,3,3,4,"out","out") 
sensor <- c(1,16,1,16,1,16,1,1,16) 
Temp <- c(35,34,92,42,21,47,42,63,12) 
df <- data.frame(date,location,sensor,Temp) 

一部のデータに値がありません。それらはNAで示されていません。彼らはちょうどデータ期間にはありません。

他の場所を無視して「4」の場所から「out」の場所を差し引いて、日付とセンサーでやりたいと思います。私は正常に私は次のようなエラーError: expecting a single valueを得る欠落日付でデータの

df %>% 
    filter(location %in% c(4, 'out')) %>% 
    group_by(date, sensor) %>% 
    summarize(Diff = Temp[location=="4"] - Temp[location=="out"], 
      location = first(location)) %>% 
    select(1, 2, 4, 3) 

ただし、次のコードですべてのデータを持っているデータの場所でこれを行っています。これは、dplyrが不足しているデータポイントに達したときに何をすべきかわからないからです。

いくつかの調査を行っていると、doのように見えますが、データフレームの値が1つも減算されずに返されます。

df %>% 
    filter(location %in% c(4, 'out')) %>% 
    group_by(date, sensor) %>% 
    do(Diff = Temp[location=="4"] - Temp[location=="out"], 
      location = first(location)) %>% 
    select(1, 2, 4, 3) 

dplyrをオーバーライドして、それを減算するエントリのいずれかを見つけることができない場合NAを返すために、それを伝える方法はありますか?

+0

で、私も、あなたのデータに同じエラーが出ます欠落している日付値はありませんが! – Rahul

+0

値がありません – hrbrmstr

答えて

1

我々はNAを返すようにしたい場合は、可能なオプションはdata.table

library(dplyr) 
df %>% 
    filter(location %in% c(4, 'out')) %>% 
    group_by(date, sensor) %>% 
    arrange(sensor, location) %>% 
    summarise(Diff = if(n()==1) NA else diff(Temp), location = first(location)) %>% 
    select(1, 2, 4, 3) 
#  date sensor location Diff 
#  <fctr> <dbl> <fctr> <dbl> 
#1 2016-03-24  1  4 21 
#2 2016-03-24  16  out NA 

と同等のオプションでは、ところで

library(data.table) 
setDT(df)[location %in% c(4, 'out')][ 
    order(sensor, location), .(Diff = if(.N==1) NA_real_ else diff(Temp), 
     location = location[1]), .(date, sensor)][, c(1, 2, 4, 3), with = FALSE] 
#   date sensor location Diff 
#1: 2016-03-24  1  4 21 
#2: 2016-03-24  16  out NA 
3
library(tidyverse) 

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") 
location <- c(1, 1, 2, 2, 3, 3, 4, "out", "out") 
sensor <- c(1, 16, 1, 16, 1, 16, 1, 1, 16) 
Temp <- c(35, 34, 92, 42, 21, 47, 42, 63, 12) 

df <- data_frame(date, location, sensor, Temp) 

# edge case helper 
`%||0%` <- function (x, y) { if (is.null(x) | length(x) == 0) y else x } 

df %>% 
    filter(location %in% c(4, 'out')) %>% 
    mutate(location=factor(location, levels=c("4", "out"))) %>%    # make location a factor 
    arrange(sensor, location) %>%           # order it so we can use diff() 
    group_by(date, sensor) %>% 
    summarize(Diff = diff(Temp) %||0% NA, location = first(location)) %>% # deal with the edge case 
    select(1, 2, 4, 3) 
## Source: local data frame [2 x 4] 
## Groups: date [1] 
## 
##   date sensor location Diff 
##  <chr> <dbl> <fctr> <dbl> 
## 1 2016-03-24  1  4 21 
## 2 2016-03-24  16  out NA