Saturday 29 August 2020

apply function in R

1)apply function:
It takes 3 arguments matrix,margin and function..

Example:
m<-matrix(c(1,2,3,4),nrow=2,ncol=2)
m
#1 indicates it is applied in row
apply(m,1,sum)

#2 indicates it is applied in column
apply(m,2,sum)
apply(m,2,mean)#2 indicates it is applied in column
apply(m,2,min)#2 indicates it is applied in column

apply(m,1,mean)#1 indicates it is applied in row

2)lapply function:
It takes list and function..

Example 1:
l<-list(a=c(1,2),b=c(3,4),c=c(5,6))
lapply(l,sum)
lapply(l,mean)

Example 2:
x<-c(4,5,9)
x
b<c("RAM","SAM","GAM")
b

3)sapply function:
It is same as lapply except it simplifies result..
It takes list and function..
Example 1:
s<-list(a=c(1,2),b=c(3,4),c=c(5,6))
sapply(l,sum)
sapply(l,mean)

4)tapply function: 
We need 3 arguments vector,factor of vector and functions..

age<-c(20,50,78,89,90)
age
gender<-c("m","m","f","m","f")
gender
f<-factor(gender)
f
tapply(age,f,sum)
tapply(age,f,mean)

where age is vector ,f is factor of vector and sum is the function

Note:sum,mean,min,max are predefind function....

1 comment:

  1. You don't realize how quickly technology is changing. Data science is highly technical and is therefore in high demand. A career in data science will open up many lucrative job opportunities. So, if you have been wanting to start your career in Data Science, now is the best time to enroll in a data science program with one of the best data science training institute in noida.

    ReplyDelete

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...