Apply functionsThe Dataminingtools.net Team
Apply functionsApply functions are used to execute a function repetitively. "Apply" functions keeps us from having to write loops to perform some operation on every row or every column of a matrix or data frame, or on every element in a list.
Apply familysapply()lapply()apply()mapply()
tapply()
rapply()UsageUsing Loops!> avg <- numeric (8)> avg[1] 0 0 0 0 0 0 0 0> for(i in 1:8)+ avg[i]<-mean(state.x77[,i])> avg[i][1] 70735.88> avg[1]  4246.4200  4435.8000     1.1700    70.8786     7.3780[6]    53.1080   104.4600 70735.8800
UsageUsing ‘apply’> apply (state.x77, 2, median)Population     Income Illiteracy   Life Exp     Murder   2838.500   4519.000      0.950     70.675      6.850    HS Grad      Frost       Area     53.250    114.500  54277.000The 2 means "go by column" -- a 1 would have meant "go by row."
UsageWe construct a function and pass it to apply. It computes the median and maximum of each column of state.x77.
Usage apply() works on each row, one at a time, to find the smallest number in each row. which() function, returns the indices within a vector for which the vector holds the value TRUE
lapplyand sapplyThe lapply() function works on any list. The "l" in "lapply" stands for "list."The "s" in "sapply" stands for "simplify."

R: Apply Functions

  • 1.
  • 2.
    Apply functionsApply functionsare used to execute a function repetitively. "Apply" functions keeps us from having to write loops to perform some operation on every row or every column of a matrix or data frame, or on every element in a list.
  • 3.
  • 4.
  • 5.
    rapply()UsageUsing Loops!> avg<- numeric (8)> avg[1] 0 0 0 0 0 0 0 0> for(i in 1:8)+ avg[i]<-mean(state.x77[,i])> avg[i][1] 70735.88> avg[1] 4246.4200 4435.8000 1.1700 70.8786 7.3780[6] 53.1080 104.4600 70735.8800
  • 6.
    UsageUsing ‘apply’> apply(state.x77, 2, median)Population Income Illiteracy Life Exp Murder 2838.500 4519.000 0.950 70.675 6.850 HS Grad Frost Area 53.250 114.500 54277.000The 2 means "go by column" -- a 1 would have meant "go by row."
  • 7.
    UsageWe construct afunction and pass it to apply. It computes the median and maximum of each column of state.x77.
  • 8.
    Usage apply() works on eachrow, one at a time, to find the smallest number in each row. which() function, returns the indices within a vector for which the vector holds the value TRUE
  • 9.
    lapplyand sapplyThe lapply() function workson any list. The "l" in "lapply" stands for "list."The "s" in "sapply" stands for "simplify."
  • 10.
    tapplytapply() is a verypowerful function that lets us break a vector into pieces and apply some function to each of the pieces. It is like sapply(), except that with sapply() the pieces are always elements of a list. With tapply() we get to specify how the breakdown is done. >tapply(barley$yield, barley$site, mean) Grand Rapids Duluth University Farm Morris Crookston Waseca 24.93167 27.99667 32.66667 35.4 37.42 48.10833