如何使用dplyr评估行中的值及其下的值?

时间:2018-12-01 00:08:49

标签: r dplyr

我有这个df:

library(dplyr)

x <- c("aa1","aa1","bb1","bb1","cc1","cc1")
y <- c(1,2,1,2,1,2)
df <- data.frame(y,x)

它看起来像这样:

  y   x
1 1 aa1
2 2 aa1
3 1 bb1
4 2 bb1
5 1 cc1
6 2 cc1

我如何使用dplyr包(突变)评估下面的行是否具有与我想要的结果相同的值:

  y   x     z
1 1 aa1  TRUE #Comparing from column x the 1st entry vs the 2nd one
2 2 aa1 FALSE #Comparing from column x the 2nd entry vs the 3rd one
3 1 bb1  TRUE #Comparing from column x the 3rd entry vs the 4th one
4 2 bb1 FALSE #...
5 1 cc1  TRUE #...
6 2 cc1 FALSE #...

2 个答案:

答案 0 :(得分:0)

您要寻找的功能是线索:

 mutate(df, z=x==lead(x))

相反,顺便说一句是lag()

为什么要知道呢,顺便说一句?我怀疑您要实现的目标是group_by()

答案 1 :(得分:0)

您甚至可以将base R与

duplicated(df$x, fromLast = TRUE)