Splitting and combining capture histories

I use the following kind of code routinely in R to go back and forth between a vector of capture history strings (ch) and a capture history matrix (chmat) and thought that some might find it useful. It differs when you can have non-numeric characters in the capture history string as with the multi-state models.
- Code: Select all
# split a vector of capture histories into a matrix when they are all numeric
chmat=t(sapply(strsplit(ch,""),function(x)as.numeric(x)))
# split a vector of capture histories into a matrix when they are alpha-numeric (as in MS designs)
chmat=do.call("rbind",strsplit(ch,""))
# reverse process to take matrix and create vector of ch strings
ch=apply(chmat,1,paste,collapse="")