lapply() and sapply()
lapply will return a list of the same length as the object (x)
basic argument structure: lapply(x, FUN,..)
wherein:
x= vector (list/atomic) or an expression
FUN= function, for ex: mean
...= optional functions
sapply() more ‘user-friendly’ mode of applying a function to each element of an object--- by default, returns a vector, matrix, or array--that is if simplify=‘array’
basic argument structure: sapply(x, FUN, ..., simplify=T, USE.NAMES=T)
wherein:
x= vector (atom/list)
FUN= function
...= additional functions
simplify= logic/character string
(can be TRUE/FALSE-- returning a simp. vector/matrix or can be =“array” and return an array)
USE.NAMES= logical, (i.e. T/F) , if =T, and X is a character, will use result as names
_____________________________________________________________
IN ACTION:
if there is a data frame (af), then: af<-data.frame(x=c(2,4,6,8,NA),y=c(14,23,5,0,1))
lapply() and coercion
(1) run a structure test-- although entered as a data frame, mode= list, but structure should be correct
> str(af) 'data.frame': 5 obs. of 2 variables: $ x: num 2 4 6 8 NA $ y: num 14 23 5 0 1
(2) add new argument lapply, coerce object, and run structural test
> af<-lapply(af,as.integer) > str(af) List of 2 $ x: int [1:5] 2 4 6 8 NA $ y: int [1:5] 14 23 5 0 1
OR > af<-lapply(af,as.character) > str(af) List of 2 $ x: chr [1:5] "2" "4" "6" "8" ... $ y: chr [1:5] "14" "23" "5" "0" ...
(4) reset af , this time use lapply() with [] to preserve original class/object
> af[]<-lapply(af,as.integer) > str(af) 'data.frame': 5 obs. of 2 variables: $ x: int 2 4 6 8 NA $ y: int 14 23 5 0 1
> af[]<-lapply(af,as.character) > str(af) 'data.frame': 5 obs. of 2 variables: $ x: chr "2" "4" "6" "8" ... $ y: chr "14" "23" "5" "0" ...
**Note: structural differences between using [] --- it keeps the data frame structure
lapply() using other functions (non-coercive)
(1) start with freshly reset data frame (af)
(2) add function of choice, print new object (af)
> af<-lapply(af,mean) > af $x [1] NA
$y ---(i.e. 14+23+0+5+1=43/5=8.6) [1] 8.6
note: remember, all operations will default to NA if an element value is NA
(3) reset af again, this time perform expressions with []
sapply()
*information drawn from cran-r library data base

















