I have a dataframe in R with a vector of non-sequential numbers (data$SiteID) that i would like to map to a vector of sequential numbers (data$site) to the unique values of data$SiteID. Within each site, I would like to map data$TrtID to 0 where data$TrtID == 'control' or to the next sequential integer, for the other unique data$TrtID‘s:
data <- data.frame(SiteID = c(1,1,1,9,'108','108','15', '15'),
TrtID = c('N', 'control', 'N', 'control', 'P', 'control', 'N', 'P'))
data$siteshould bec(1,1,1,2,3,3,4,4).data$trtshould bec(1,0,1,0,1,0,0,1).
Use conversion of factors to integers:
If the ordering is important, you can give specific orders to the levels:
Modified version grouping trt factor by site: