vanao veneri vanao veneri - 12 days ago 5
R Question

Consecutive numbering of data.frame segments

I wanted to assign consecutive numbers to segments of my data.frame. I tried like so:

library(plyr)
ex1 <- mtcars
ehh <- ddply(.data=ex1, .variables=c("cyl"), transform, brx_j = c(1:nrow(cyl)))


But it's an "Error in data.frame(list(mpg = c(22.8, 24.4, 22.8, 32.4, 30.4, 33.9, 21.5, :
arguments imply differing number of rows: 11, 0".

What's my mistake here?

Answer

We need seq_along instead of 1:nrow as 'cyl' is a single column and not a data.frame.

ddply(.data=ex1, .variables=c("cyl"), transform, brx_j = seq_along(cyl))

and with dplyr, there is row_number() function to get the sequence after grouping by 'cyl'.

library(dplyr)
ex1 %>%
     group_by(cyl) %>% 
     mutate(brx_j = row_number())