[R] Identify first row of each ID within a data frame, create a variable first =1 for the first row and first=0 of all other rows
Christopher W. Ryan
cry@n @end|ng |rom b|ngh@mton@edu
Sun Dec 1 03:51:48 CET 2024
Sorry, for completeness:
library(dplyr)
olddata %>% group_by(ID) %>% mutate(first = as.integer(row_number() == 1))
--Chris Ryan
Christopher W. Ryan wrote:
> Personally, I'd do this in the tidyverse with dplyr and its row_number()
> function.
>
> olddata %>% group_by(ID) %>% mutate(first = as.integer(row_number() == 1))
>
> --Chris Ryan
>
> Sorkin, John wrote:
>> ID <- c(rep(1,10),rep(2,6),rep(3,2))
>> date <- c(rep(1,2),rep(2,2),rep(3,2),rep(4,2),rep(5,2),
>> rep(5,3),rep(6,3),rep(10,2))
>> olddata <- data.frame(ID=ID,date=date)
More information about the R-help
mailing list