Share

10.10 Grab text included in strings of varying lengths

#This grabs the last character of a string that has different lengths. For example, #a vector of animal ID along with sex 
#Code courtesy of D. Diefenbach, PA Coop Unit
#First read in a table with string as a factor
locweather <-read.table(file="locweather.txt",header=T, stringsAsFactors=FALSE)

#Create new variable by pasting last digit of variable regardless of variable #length (i.e., number of characters)

sex <- as.factor(substr(locweather$indlocalident,nchar(locweather$indlocalident),
nchar(locweather$indlocalident)))
#This will change a vector from this:
#3455F
#21M
#44890F
#Returning a vector ’sex’
#F
#M
#F