如果条件和复制来自不同行的值

时间:2016-12-17 17:22:48

标签: r if-statement conditional

我有以下数据:

Data <- data.frame(Project=c(123,123,123,123,123,123,124,124,124,124,124,125,125,125),
               Name=c("Harry","David","David","Harry","Peter","Peter","John","Alex","Alex","Mary","Mary","Dan","Joe","Joe"),
                      Value=c(1,4,7,3,8,9,8,3,2,5,6,2,2,1),
                      OldValue=c("","Open","In Progress","Complete","Open","In Progress","Complete","Open","In Progress","System Declined","In Progress","","Open","In Progress"),
                      NewValue=c("Open","In Progress","Complete","Open","In Progress","Complete","Open","In Progress","System Declined","In Progress","Complete","Open","In Progress","Complete"))

The data should look like this

我想创建另一个名为EditedBy的列,它应用以下逻辑。

  1. 如果第1行中的项目等于第2行中的项目,则第1行中的新值等于&#34;打开&#34;然后从第2行获取名称。如果前两个条件中的任何一个为False,则在第一行中保留名称。
  2. So the data should look like this

    我该怎么做?

1 个答案:

答案 0 :(得分:1)

我们可以使用data.table

执行此操作
library(data.table)
setDT(Data)[, EditedBy := Name[2L] ,.(Project, grp=cumsum(NewValue == "Open"|
                         shift(NewValue == "System Declined", fill=TRUE)))]

Data
# Project  Name Value        OldValue        NewValue EditedBy
# 1:     123 Harry     1                            Open    David
# 2:     123 David     4            Open     In Progress    David
# 3:     123 David     7     In Progress        Complete    David
# 4:     123 Harry     3        Complete            Open    Peter
# 5:     123 Peter     8            Open     In Progress    Peter
# 6:     123 Peter     9     In Progress        Complete    Peter
# 7:     124  John     8        Complete            Open     Alex
# 8:     124  Alex     3            Open     In Progress     Alex
# 9:     124  Alex     2     In Progress System Declined     Alex
#10:     124  Mary     5 System Declined     In Progress     Mary
#11:     124  Mary     6     In Progress        Complete     Mary
#12:     125   Dan     2                            Open      Joe
#13:     125   Joe     2            Open     In Progress      Joe
#14:     125   Joe     1     In Progress        Complete      Joe