2017-01-19 38 views
1

我有三列日期。重排日期r

test <- data.frame(a = as.Date(rep("2008-02-04", 5)), 
       b = as.Date(c("2010-01-25", 
          "2012-04-13", 
          "2013-04-04", 
          "2013-09-06", 
          "2014-08-14")), 
       c = as.Date(c("2010-01-29", 
          "2012-04-16", 
          NA, 
          "2013-09-19", 
          "2014-08-21"))); test 
      a   b   c 
1 2008-02-04 2010-01-25 2010-01-29 
2 2008-02-04 2012-04-13 2012-04-16 
3 2008-02-04 2013-04-04  <NA> 
4 2008-02-04 2013-09-06 2013-09-19 
5 2008-02-04 2014-08-14 2014-08-21 

我想重新安排他們在以下位置。會發生什麼事情,我把行A的值替換爲前一行的C值。並且在前面的行C是NA的情況下,比從前面的行B的值被取出並放置到當前的a中。

  a   b   c 
1 2008-02-04 2010-01-25 2010-01-29 
2 2010-01-29 2012-04-13 2012-04-16 
3 2012-04-16 2013-04-04  <NA> 
4 2013-04-04 2013-09-06 2013-09-19 
5 2013-09-19 2014-08-14 2014-08-21 

到目前爲止,我已經有解決這個for循環:

n <- nrow(test) 
if (n > 1) { 
    for (i in 1:(n - 1)) { 
    empty <- is.na(test$c[i]) 
    if (empty) 
     test$a[i + 1] <- test$b[i] 
    else 
     test$a[i + 1] <- test$c[i] 
    } 
} 

我想知道是否有使用dplyr包來做到這一點任何更快的方法。我想用ifelse語句使用mutate,但我不知道如何爲我想要更改的變量選擇i + 1。我tryed做到以下幾點:

test %>% mutate(a = if_else(is.na(lag(c, n = 1)), 
          true = lag(b, n = 1), 
          false = lag(c, n = 1), 
          missing = a)) 

但這始終返回NA的第一個項目中排:

  a   b   c 
1  <NA> 2010-01-25 2010-01-29 
2 2010-01-29 2012-04-13 2012-04-16 
3 2012-04-16 2013-04-04  <NA> 
4 2013-04-04 2013-09-06 2013-09-19 
5 2013-09-19 2014-08-14 2014-08-21 

回答

1

嘗試dplyr::coalesce。它返回它的參數逐個分量中的第一個非NA值:

test %>% mutate(a = coalesce(lag(c), lag(b), a)) 

捐贈:

  a   b   c 
1 2008-02-04 2010-01-25 2010-01-29 
2 2010-01-29 2012-04-13 2012-04-16 
3 2012-04-16 2013-04-04  <NA> 
4 2013-04-04 2013-09-06 2013-09-19 
5 2013-09-19 2014-08-14 2014-08-21 
+0

謝謝'coalesce'功能,你能包括的'coalesce'與執行時間比較向量計算即''conditionVal = as.Date(ifelse(!is.na(lag(test $ c)),lag(test $ c),lag(test $ b)));測試$ a = as.Date(ifelse(is.na(conditionVal),test $ a,conditionVal))' – OdeToMyFiddle

+0

非常感謝。 – ogiz

+0

@ogiz,如果解決方案令人滿意,您可以點擊左側接受它 – OdeToMyFiddle