1

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?

vanao veneri
  • 970
  • 2
  • 12
  • 31

2 Answers2

2

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())
akrun
  • 874,273
  • 37
  • 540
  • 662
1

This will also work (base R):

ex1$brx_j <- ave(1:nrow(ex1), ex1$cyl, FUN=seq_along)
ex1[order(ex1$cyl),]
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63