Apply,Sapply,Lapply

rahul_j03 · updated October 12, 2022
R
Fork
#APPLY FUNCTION 

#create a data frame with three columns and five rows
data <- data.frame(a = c(1, 3, 7, 12, 9),
                   b = c(4, 4, 6, 7, 8),
                   c = c(14, 15, 11, 10, 6))
data



#find the sum of each row
apply(data, 1, sum)



#find the sum of each column
apply(data, 2, sum)


#find the mean of each row
apply(data, 1, mean)


#find the mean of each column, rounded to one decimal place
round(apply(data, 2, mean), 1)

#find the standard deviation of each row
apply(data, 1, sd)


#find the standard deviation of each column
apply(data, 2, sd)


#LAPPLY FUNCTION
#Use the lapply() function when you want to apply a function to each element of a list, vector, or data frame and obtain a list as a result.


lapply(data, mean)

#multiply values in each column by 2 and return results as a list
lapply(data, function(data) data*2)

lapply(data, sum)
lapply(data,mean)
lapply(data,function(x) x*5)


#SAPPLY 
#Use the sapply() function when you want to apply a function to each element of a list, vector, or data frame and obtain a vector instead of a list as a result.

#find mean of each column and return results as a vector
sapply(data, mean)

#multiply values in each column by 2 and return results as a matrix
sapply(data, function(data) data*2)

#sapply()can also be used to perfom operations on lists
x <- list(a=1, b=1:5, c=1:10) 
x

#find the sum of each element in the list
sapply(x, sum)

#find the mean of each element in the list
sapply(x, mean)

#TAPPLY()

head(iris)

#find the max Sepal.Length of each of the three Species
tapply(iris$Sepal.Length, iris$Species, max)

#find the mean Sepal.Width of each of the three Species
tapply(iris$Sepal.Width, iris$Species, mean)

#find the minimum Petal.Width of each of the three Species
tapply(iris$Petal.Width, iris$Species, min)


Output

Comments

Please sign up or log in to contribute to the discussion.