R dplyr逐行执行

时间:2017-02-24 01:18:56

标签: r dplyr

我正在寻找一种使用的执行逐行语句的方法 R中的dplyr包,类似于循环执行:只有在前一行更新时,我们才对下一行执行某些操作。

例如,

X <- data.frame(a = c(1,NA,NA,NA))
for (i in 2:nrow(X)){
    X$a[i] = X$a[i-1] + 1     
}
X
  a
1 1
2 2
3 3
4 4

因此,只有当第2行在前一个循环步骤中收到值= 2时,第3行才从前一行中获取值。

如果我尝试通过dplyr::mutate函数执行此操作,那么我有

library(dplyr)
X <- data.frame(a = c(1,NA,NA,NA))
X %>% mutate(a = if_else(row_number() == 1, a, lag(a) + 1) )
   a
1  1
2  2
3 NA
4 NA

如何使用dplyr获取第一个输出?

让我举一些具体而复杂的例子:

> X <- data.frame(date_1 = c("2000-01-01", "2001-01-01", NA, NA, NA, "2007-01-01", NA, NA),
+                 date_2 = c("2002-01-01", "2002-01-01", "2002-01-01", "2002-01-01", "2003-01-01", "2008-01-01", "2010-01-01", "2010-01-01"),
+                 stringsAsFactors=FALSE)
> X
      date_1     date_2
1 2000-01-01 2002-01-01
2 2001-01-01 2002-01-01
3       <NA> 2002-01-01
4       <NA> 2002-01-01
5       <NA> 2003-01-01
6 2007-01-01 2008-01-01
7       <NA> 2010-01-01
8       <NA> 2010-01-01
>

我希望使用以下循环填充它:

> for (i in 2:nrow(X)){
+      X$date_1[i] <- if_else(!is.na(X$date_1[i]), X$date_1[i],
+                       if_else(X$date_2[i-1] == X$date_2[i], X$date_1[i-1],  X$date_2[i-1]))
+ }
> X
      date_1     date_2
1 2000-01-01 2002-01-01
2 2001-01-01 2002-01-01
3 2001-01-01 2002-01-01
4 2001-01-01 2002-01-01
5 2002-01-01 2003-01-01
6 2007-01-01 2008-01-01
7 2008-01-01 2010-01-01
8 2008-01-01 2010-01-01

dplyr版本看起来像:

> X %>% mutate( date_1 = if_else(row_number() == 1, date_1,
+                         if_else(!is.na(date_1), date_1,
+                          if_else(date_2 == lag(date_2), lag(date_1),
+                                  lag(date_2))))
+         )
      date_1     date_2
1 2000-01-01 2002-01-01
2 2001-01-01 2002-01-01
3 2001-01-01 2002-01-01
4       <NA> 2002-01-01
5 2002-01-01 2003-01-01
6 2007-01-01 2008-01-01
7 2008-01-01 2010-01-01
8       <NA> 2010-01-01

1 个答案:

答案 0 :(得分:1)

尝试:

library(tidyverse)


x %>%
    fill(a) %>%
    mutate(a = a+seq_along(a)-1)

x %>%
    fill(a) %>%
    mutate(a = a+which(!!a)-1)

那应该产生:

#  a
#1 1
#2 2
#3 3
#4 4

编辑:

最新示例的解决方案:

X <- data.frame(date_1 = c("2000-01-01", "2001-01-01", NA, NA, NA, "2007-01-01", NA, NA),
                date_2 = c("2002-01-01", "2002-01-01", "2002-01-01", "2002-01-01", "2003-01-01","2008-01-01", "2010-01-01", "2010-01-01"), stringsAsFactors=FALSE)

X %>%
    group_by(date_2) %>%
    fill(date_1) %>%
    ungroup() %>%
    mutate(date_3 = lag(date_2)) %>%
    group_by(date_1, date_2) %>%
    mutate(date_3 = if_else(is.na(date_1), head(date_3,1), date_3)) %>%
    ungroup() %>%
    mutate(date_1 = if_else(is.na(date_1), date_3, date_1)) %>%
    select(date_1, date_2)

输出:

 date_1     date_2    
 2000-01-01 2002-01-01
 2001-01-01 2002-01-01
 2001-01-01 2002-01-01
 2001-01-01 2002-01-01
 2002-01-01 2003-01-01
 2007-01-01 2008-01-01
 2008-01-01 2010-01-01
 2008-01-01 2010-01-01

我希望这会有所帮助。