将行数计数到特定值并反向计数

问题描述

我有这个数据

data.frame(x1 = c(rep(0,3),rep(1,4),rep(0,4)))

我想这样数:

X2 列

enter image description here

谁能解释一下我该怎么做?谢谢!

解决方法

这是带有 rle 的一个选项:

df <- data.frame(x1 = c(rep(0,3),rep(1,4),rep(0,4)))

df$x2 <- unlist(with(rle(df$x1),mapply(function(x,y) 
                if(x == 0) rev(-seq(y)) else seq(y) - 1,values,lengths)))
df

#   x1 x2
#1   0 -3
#2   0 -2
#3   0 -1
#4   1  0
#5   1  1
#6   1  2
#7   1  3
#8   0 -4
#9   0 -3
#10  0 -2
#11  0 -1

这也可以在 ave 的帮助下编写:

df$x2 <- ave(df$x1,data.table::rleid(df$x1),FUN = function(x) 
              if(x[1] == 0) rev(-seq_along(x)) else seq_along(x) - 1)

两个代码的逻辑是一样的。我们创建连续 0 和 1 值的组,如果组值为 0,则创建从 1 到组长度的序列,使其为负值并反转值。如果组值为 1,则创建从 0 到组长度 - 1 的序列。

,

我们可以使用 { "idNotaMateria": 5,"idMateria": 7,"idUsuario": 7,"notaMateria": 8.0,"tipoNota": "winx" },{ "idNotaMateria": 2,"idMateria": 11,"notaMateria": 2.0,{ "idNotaMateria": 4,"tipoNota": "Net" } 中的 { "idNotaMateria": 2,"notaMateria": 5.0,(avarege with notaMateria) "tipoNota": "winx",(gruoping to tipoNota) "materia": "IN" (add camp condition list2.idMateria =list1.idMateria) },{ "idNotaMateria": 4,(avarege with notaMateria) "tipoNota":"Net",(gruoping to tipoNota) "materia": "PT" (add camp condition list2.idMateria =list1.idMateria) }

rleid

-输出

data.table