官术网_书友最值得收藏!

  • Hands-On Data Science with R
  • Vitor Bianchi Lanzetta Nataraj Dasgupta Ricardo Anjoleto Farias
  • 289字
  • 2021-06-10 19:12:35

Applying families of functions 

The apply family of functions allow users to easily apply custom vector functions on matrices, lists, and other R data structures. Operations such as summing by rows and columns or more complex ones, such as functions with conditional logic, can be applied using apply commands. These are extremely convenient, not only from an ease-of-use perspective but also from a performance standpoint. In general, vectorised operations will almost always be faster and more efficient than looping, such as with for-next loops in R:

# apply 
 
# Usage 
#  
# apply(X, MARGIN, FUN, ...) 
# Arguments 
#  
# X: an array, including a matrix. 
# MARGIN: a vector giving the subscripts which the function will be applied over. E.g., for a matrix 1 indicates  
# rows, 2 indicates columns, c(1, 2) indicates rows and columns. Where X has named dimnames, it can be a  
# character vector selecting dimension names. 
 
apply(state[,-ncol(state)], 2, sum) # Sum of all values in the numeric columns 
apply(state[,-ncol(state)], 2, mean) # Mean of all values in the numeric columns 

The output is as follows:

lapply, which belongs to the apply family of functions, is used to the apply functions on lists in R:

# lapply - list apply which is similar to apply, but can be also used for other R object types
## Produces the output as a list
lapply(state[,-ncol(state)], function(x) {list(MIN=min(x), MAX=max(x), MEAN=mean(x))})

The output is as follows:

 sapply—it provides the same functionality as lapply but, instead of a list output, sapply returns the result as a vector:

# sapply - simplifies the output (eg., produce a vector instead of a list) 
sapply(state[,-ncol(state)], function(x) {list(MIN=min(x), MAX=max(x), MEAN=mean(x))}) 

The output of the preceding code is as follows:

主站蜘蛛池模板: 潼关县| 郑州市| 通榆县| 谢通门县| 青田县| 阳新县| 梅河口市| 九台市| 公安县| 栖霞市| 达拉特旗| 康保县| 田东县| 苗栗县| 鄢陵县| 安丘市| 南雄市| 甘孜县| 呼图壁县| 沙坪坝区| 沁水县| 临洮县| 太仆寺旗| 石楼县| 中阳县| 凌源市| 沁源县| 砀山县| 察雅县| 平顶山市| 曲周县| 曲靖市| 西安市| 行唐县| 醴陵市| 英超| 奉化市| 嘉善县| 乐亭县| 加查县| 石柱|