Saturday, October 15, 2011

sapply()

sapply() is a handy function for applying a function repeatedly to items in a vector or list.

sapply() has a simple syntax: sapply(x, function)

where x can be a list, vector, matrix, etc, and function can be a stock function from R or one that you write yourself. Functions could be nchar(), length(), is(), class(), etc.

For example, say we have a vector with the names of states

states<-c("Washington","Oregon","Idaho","Montana","California","Wyoming","Utah","Colorado","New Mexico", "North Dakota", "South Dak0ta", "Nebraska", "Kansas", "Kentucky", "Illinois", "Iowa", "Michigan", "Minnesota", "Wisconsin", "Pennsylvania", "West Virginia", "Virginia", "New York", "Maine", "Rhode Island", "Connecticut", "North Carolina", "South Carolina", "Mississippi", "Texas", "Florida", "Alabama", "Missouri", "Nevada", "Hawaii", "Alaska", "Tennessee", "Arkansas", " New Jersey", "Massachusetts", "Vermont", "New Hampshire", "Ohio", "Indiana", "Arizona", "Georgia", "Oklahoma", "Delaware", "Maryland", "Louisiana")

and you want to know how many letters are in the name of each state. You could use the nchar() function, which counts the number of characters in an object.

sapply(states, nchar)

No comments:

Post a Comment