Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save brandmaier/5385ccd7e672f1bbf0025154c1f9aa31 to your computer and use it in GitHub Desktop.
Save brandmaier/5385ccd7e672f1bbf0025154c1f9aa31 to your computer and use it in GitHub Desktop.
R: Create sorted numeric IDs in a datafile with alphanumeric IDs
# we simulate a data set with an alphanumeric ID column and some
# observed values x
# The goal is to give out new participant IDs with consecutive numbers
# starting from 1 (while maintaining the original order)
dat <- data.frame(id=c("P1","P1","P1","second","second","second","3rd","no4","no4"),
x=rnorm(9))
# convert IDs to a factor and then use position of factor level as new ID
# /!\ this yields ID that are according to alphanumeric sorting of original IDs
dat$numeric_id <- as.numeric(factor(dat$id))
print(dat)
# if you want IDs to match the original order, explicitly state
# that the levels correspond to the original ordering of unique
# values
dat$numeric_id <- as.numeric(factor(dat$id,levels = unique(dat$id)))
print(dat)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment