当逻辑检查列的尾部和头部值时,Mutate和ifelse()会失败

时间:2016-11-17 05:07:15

标签: r dplyr

我有一个数据框,我希望通过条件检查另一列的extail值来添加新列head。如果条件匹配,请插入{{1或ex1到新列。 这就是我的意思

ex2

我试过

库(dplyr)

x = rep(c(seq(1,3),seq(2,3)),2)
grp=gl(2,5)
df <- data.frame(x,grp)


#       x grp
#    1  1   1
#    2  2   1
#    3  3   1
#    4  2   1
#    5  3   1
#    6  1   2
#    7  2   2
#    8  3   2
#    9  2   2
#    10 3   2

预期产出

dff <- df%>%
group_by(grp)%>%
mutate(ex=ifelse(tail(x,2)==c(2,3),tail(ex,2)="ex2"&head(ex,3)="ex1",NA))

>Error: unexpected '=' in:
"group_by(grp)%>%
mutate(ex=ifelse(tail(x,2)==c(2,3),tail(ex,2)="

我该怎么做?

1 个答案:

答案 0 :(得分:1)

我们可以尝试data.table

library(data.table)
i1 <- setDT(df)[, .I[tail(seq_len(.N),2)] , grp]$V1
df[, ex:= "ex1"]
df[df[i1, .I[x==c(2,3)] , grp]$V1, ex := "ex2"]
df
#   x grp  ex
#1: 1   1 ex1
#2: 2   1 ex1
#3: 3   1 ex1
#4: 2   1 ex2
#5: 3   1 ex2
#6: 1   2 ex1
#7: 2   2 ex1
#8: 3   2 ex1
#9: 2   2 ex2
#10:3   2 ex2

或使用dplyr

library(dplyr)
df %>% 
   group_by(grp) %>%
   mutate(x1 = rep(c(0, 2,3), c(n()-2, 1, 1)), 
          ex = if_else(x1==x & row_number() %in% tail(row_number(), 2), "ex2", "ex1")) %>%
   select(-x1)
#      x    grp    ex
#   <int> <fctr> <chr>
#1      1      1   ex1
#2      2      1   ex1
#3      3      1   ex1
#4      2      1   ex2
#5      3      1   ex2
#6      1      2   ex1
#7      2      2   ex1
#8      3      2   ex1
#9      2      2   ex2
#10     3      2   ex2