What is apply function in R?
MACHINE LEARNING RECIPES DATA CLEANING PYTHON DATA MUNGING PANDAS CHEATSHEET     ALL TAGS

# What is apply function in R?

This recipe explains what is apply function in R

0

## Recipe Objective

Problem: Iteration through a long list or vector using a for loop takes tremendous amount of time.

This problem is solved by using apply family of functions in R. This family of functions can be fed with many built-in functions to perform different tasks on the collection of objects such as list, vector, dataframe etc.

The family of apply functions are listed below:

1. apply()
2. lapply()
3. sapply()
4. tapply()

apply() is a function that takes a matrix or dataframe as input and gives the output in vector or array by appplying a certain operation on it.

This recipe demonstrates how to use the apply() using dataframe as input

Dataset description: It is the basic data about the customers going to the supermarket mall. The variable that we interested in is Annual.Income which is in 1000s and Spending Score

``` # Data manipulation package library(tidyverse) ​ # reading a dataset customer_seg = read.csv('R_72_Mall_Customers.csv') ​ glimpse(customer_seg) ```
```Rows: 200
Columns: 5
\$ CustomerID              1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 1...
\$ Gender                  Male, Male, Female, Female, Female, Female, ...
\$ Age                     19, 21, 20, 23, 31, 22, 35, 23, 64, 30, 67, ...
\$ Annual.Income..k..      15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 19, ...
\$ Spending.Score..1.100.  39, 81, 6, 77, 40, 76, 6, 94, 3, 72, 14, 99,...
```

## Step 2: Using apply()

Using the apply() with the following syntax:

apply(X, MARGIN, FUN)

where:

1. X = data frame or matrix ;
2. MARGIN = an argument which represents the dimension in which the operation should take place (row or column wise). 1 for row-wise and 2 for column wise ;
3. FUN = function that needs to be applied on every element of the dataframe
``` # applying sum function on 2 columns "Annual income" and "spending score" result = apply(customer_seg[,c("Annual.Income..k..","Spending.Score..1.100.")], MARGIN = 2, FUN = sum) ​ result ```
```Annual.Income..k..12112Spending.Score..1.100.10040
```

#### Relevant Projects

##### Forecast Inventory demand using historical sales data in R
In this machine learning project, you will develop a machine learning model to accurately forecast inventory demand based on historical sales data.

##### Ensemble Machine Learning Project - All State Insurance Claims Severity Prediction
In this ensemble machine learning project, we will predict what kind of claims an insurance company will get. This is implemented in python using ensemble machine learning algorithms.

##### Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.

##### Census Income Data Set Project - Predict Adult Census Income
Use the Adult Income dataset to predict whether income exceeds 50K yr based on census data.

##### Predict Macro Economic Trends using Kaggle Financial Dataset
In this machine learning project, you will uncover the predictive value in an uncertain world by using various artificial intelligence, machine learning, advanced regression and feature transformation techniques.

##### Build an Image Classifier for Plant Species Identification
In this machine learning project, we will use binary leaf images and extracted features, including shape, margin, and texture to accurately identify plant species using different benchmark classification techniques.

##### Data Science Project in Python on BigMart Sales Prediction
The goal of this data science project is to build a predictive model and find out the sales of each product at a given Big Mart store.

##### Build a Music Recommendation Algorithm using KKBox's Dataset
Music Recommendation Project using Machine Learning - Use the KKBox dataset to predict the chances of a user listening to a song again after their very first noticeable listening event.

##### Perform Time series modelling using Facebook Prophet
In this project, we are going to talk about Time Series Forecasting to predict the electricity requirement for a particular house using Prophet.

##### Customer Churn Prediction Analysis using Ensemble Techniques
In this machine learning churn project, we implement a churn prediction model in python using ensemble techniques.