Create indicator

I would like to create a numerical indicator for such a matrix that for each unique element in one variable it creates a sequence of length based on the element in another variable. For instance:

frame<- data.frame(x = c("a", "a", "a", "b", "b"), y = c(3,3,3,2,2))
frame
  x y
1 a 3
2 a 3
3 a 3
4 b 2
5 b 2

The z indicator should look like this:

  x y z
1 a 3 1
2 a 3 2
3 a 3 3
4 b 2 1
5 b 2 2

Any help is greatly appreciated. Thank.

+3
source share
5 answers

No ave?

frame$z <- with(frame, ave(y,x,FUN=seq_along) )
frame

#  x y z
#1 a 3 1
#2 a 3 2
#3 a 3 3
#4 b 2 1
#5 b 2 2

Version A data.tablemay be something like lower (thanks to @mnel):

#library(data.table)
#frame <- as.data.table(frame)
frame[,z := seq_len(.N), by=x]

My initial thought was to use:

frame[,z := .SD[,.I], by=x]

.SD data.table split by x. .I data.table. , .SD[,.I] . , @mnel, , .SD , .

+4

:

frame$z <- unlist(lapply(rle(as.numeric(frame[, "x"]))$lengths, seq_len))
+2
library(dplyr)
frame %.%
  group_by(x) %.%
  mutate(z = seq_along(y))
+2

data.frame x :

> frame$z <- unlist(lapply(split(frame, frame$x), function(x) 1:nrow(x)))
> frame
  x y z
1 a 3 1
2 a 3 2
3 a 3 3
4 b 2 1
5 b 2 2

data.table:

library(data.table)
frame <- data.table(frame)[,z:=1:nrow(.SD),by=x]
+1

Try where x- this is the column by which the grouping should be performed, and y- any numeric column. if there are no numeric columns, use seq_along(x), say, instead of y:

transform(frame, z = ave(y, x, FUN = seq_along))
+1
source

All Articles