How to calculate number of years per country in R? -
this question has answer here:
what easiest way calculate number of years per country in r? please see sample below. 1) how can create "#years" variable? observation period in real data 1990 2010, years ordered ascendingly.
2) also, possible start "0", instead of "1"?
country year #years 2000 1 2001 2 2002 3 b 2000 1 b 2001 2 b 2002 3
here 1 option ave
base r
years <- with(df1, ave(year, country, fun=seq_along))
if need start 0
years <- years -1 df1$years <- years
an option using data.table
library(data.table) setdt(df1)[, years := seq_len(.n), country]
Comments
Post a Comment