Skip to content

Instantly share code, notes, and snippets.

@abelsonlive
Created May 27, 2012 02:33
Show Gist options
  • Save abelsonlive/2796460 to your computer and use it in GitHub Desktop.
Save abelsonlive/2796460 to your computer and use it in GitHub Desktop.
Automatically generate variable names from Pattern, R
#// Say you were building a dataset and wanted to automatically
#// generate variable names by some pattern.
#// For instance, you might want to do this with population counts
#// within 100 census tracts by race
#// IE:
#
# tracts <- paste("c", rep(1:100), sep="")
# race - c("black", "white", "hispanic")
#
#// In this case you would want to generate 300 unique variable names
#// This function will generate these variable names automatically
# when provided with:
#
# 1. the "roots" - in the example above, the unique census tracts
# 2. the "vars" - in the example above, the unique races
#// see below for the example:
tracts <- paste("c", rep(1:100), sep="")
races <- c("blk", "wht", "hsp")
genVarNames <- function(roots, vars, delim="_"){ #delim can also be defined as "." or ""
n.roots <- length(roots)
n.vars <- length(vars)
tot.vars <- n.roots*n.vars
instances <- seq(0,tot.vars, by=n.vars) + 1
varnames <- character(tot.vars)
for (i in instances){
range <- (i+(n.vars-1))
j <- range/n.vars
varnames[i:range]<- paste(roots[j], delim, vars[1:n.vars], sep="")
}
varnames <- varnames[-c((length(varnames)-(n.vars-1)):length(varnames))]
return(varnames)
}
genVarNames(tracts, races)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment