Apply function family

Time:2022-1-14
#apply(X,MARGIN,FUN,...)
#Sum by row
apply(df,1,sum)
#Sum by column
apply(df,2,sum)
#Reassign all elements in DF
apply(df,c(1,2),function(x){x<-100})
#Calculate the mean, variance and maximum value of each column in DF (see the figure below for apply method and for method)
apply(df,2,function(x){c(mean(x),var(x),max(x))})
#Write a user-defined function and apply to find the mean, variance and maximum of each column in DF
fun_1<_function(x){
           c(mean(x),var(x),max(x))
}
apply(df,2,fun_1)
#Sum of cubes by column
apply(df,2,function(x){sum(x^3)})
#Calculate the mean value of each subset of the data in the list (the lapply method and the for method are shown in the figure below)
lapply(list,mean)       
A simplified version of the sapply (list, mean) #lapply function. The output result is a vector
Apply (list, mean, Na. RM = t) # if there is missing value in the data, calculate after removing the missing value.
#The application of map can input multiple parameters at a time, or a parameter needs to pass in a vector to operate on each value.
mapply(function(x,y){x^y},c(2,2),c(2,1))
#Comprehensive application, custom chimeric function
sapply(list(mean,var,max),
       function(x){apply(data,2,x)},
        simplify=T)

① Basic usage of apply function

The apply function cannot be applied to a list.

Apply function family

Apply function result diagram png

② Calculate the mean, variance and maximum of each column in DF (for function method)

Apply function family

For method png

③ Calculate the mean, variance and maximum of each column in DF (apply method)

Apply function family

Apply method png

④ Processing method of missing value Na in data (Application of apply function)

Apply function family

After apply processes the data with missing values and interprets fun The meaning of png

⑤ Write a user-defined function and apply to find the mean, variance and maximum of each column in DF

Apply function family

Write custom functions and apply png

⑥ Find the mean of each subset of the data in the list (for method)

Apply function family

① For method png

Apply function family

② For method png

⑦ Find the mean of each subset of the data in the list (lapply method)

Apply apply to list and data frame. The output form is list.
Lapply (frame, mean) obtains the average value of each column in the frame data output in the form of list

Apply function family

① Lapply method png

Apply function family

② Lapply method png

Sapply is a simplified version of sapply, and the output results are presented in the form of vectors.

⑧ Application of map

Moreargs (list (1,2)) means constant a = 1, B = 2

Apply function family

mapply.png

⑨ Comprehensive application, custom chimeric function

sapply(list(mean,var,max),function(x){apply(data,2,x)},simplify=T)

Apply function family

Custom chimeric function png