The Wayback Machine - https://web.archive.org/web/20240828110755/https://www.geeksforgeeks.org/setting-up-environment-for-machine-learning-with-r-programming/
Open In App

Setting up Environment for Machine Learning with R Programming

Last Updated : 22 Jul, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Machine Learning is a subset of Artificial Intelligence (AI), which is used to create intelligent systems that are able to learn without being programmed explicitly. In machine learning, we create algorithms and models which is used by an intelligent system to predict outcomes based on particular patterns or trends which are observed from the given data. Machine learning follows a unique principle of using data and the outcomes from the data to predict the rules which are stored in a model. This model is then used to predict outcomes from a different set of data. In R programming the environment for machine learning can be set easily through RStudio.

Setting up an environment for machine learning using Anaconda

Step 1: Install Anaconda (Linux, Windows) and launch the navigator.

Step 2: Open Anaconda Navigator and click the Install button for Rstudio.
anaconda-navigator

Step 3: After installation, create a new environment. Anaconda will then send a prompt asking to enter a name for the new environment and the lunch the R studio.
create-new-environment

Running R commands

Method 1: R commands can run from the console provided in R studio. After opening Rstudio simply type R commands to the console.
running-R-command

Method 2: R commands can be stored in a file and can be executed in an anaconda prompt. This can be achieved by the following steps.

  1. Open an anaconda prompt
  2. Go to the directory where the R file is located
  3. Activate the anaconda environment by using the command:
    conda activate <ENVIRONMENT_NAME>
  4. Run the file by using the command:
     Rscript <FILE_NAME>.R

running-R-command-in-anaconda-console

Installing machine learning packages in R

Packages help make code easier to write as they contain a set of predefined functions that perform various tasks. The most used machine learning packages are Caret, e1071, net, kernlab, and randomforest. There are two methods that can be used to install these packages for your R program.

Method 1: Installing Packages through Rstudio

  1. Open Rstudio and click the Install Packages option under Tools which is present in the menubar.
    install-packages
  2. Enter the names of all the packages you want to install separated by spaces or commas and then click install.
    install-packages
  3. Method 2: Installing Packages through Anaconda prompt/Rstudio console

    1. Open an Anaconda prompt.
    2. Switch the environment to the environment you used for Rstudio using the command:
      conda activate <ENVIRONMENT_NAME>
    3. Enter the command r to open the R console.
    4. Install the required packages using the command:
      install.packages(c("<PACKAGE_1>", "<PACKAGE_2>", ..., "<PACKAGE_N>"))

    installing-R-packages

    While downloading the packages you might be prompted to choose a CRAN mirror. It is recommended to choose the location closest to you for a faster download.
    ML with R

    Machine Learning packages in R

    There are many R libraries that contain a host of functions, tools, and methods to manage and analyze data. Each of these libraries has a particular focus with some libraries managing image and textual data, data manipulation, data visualization, web crawling, machine learning, and so on. Here let’s discuss some of the important machine learning packages by demonstrating an example.

    Example:

    Preparing the Data Set:
    Before using these packages first of all import the data set into RStudio, cleaning the data set, and split the data into train and test data set. Download the CSV file from this link.




    # Import the data set
    Data <- read.csv("GenderClassification.csv",
                      stringsAsFactors = TRUE)
    # Using set.seed()
    # Generating random number
    set.seed(10)
      
    # Cleaning the data set
    Data$Favorite.Color <- as.numeric
                              (Data$Favorite.Color)
    Data$Favorite.Music.Genre <- as.numeric
                              (Data$Favorite.Music.Genre)
    Data$Favorite.Beverage <- as.numeric
                              (Data$Favorite.Beverage)
    Data$Favorite.Soft.Drink <- as.numeric
                              (Data$Favorite.Soft.Drink)
      
    # Split into train and test data set
    TrainingSize <- createDataPartition(Data$Gender, 
                                        p = 0.8, 
                                        list = FALSE)
    TrainingData <- Data[TrainingSize,]
    TestingData <- Data[-TrainingSize,]

    
    

    CARET: Caret stands for classification and regression training. The CARET package is used for performing classification and for regression tasks. It consists of many other built-in packages.




    # Using CARET package
      
    # Importing the library
    library(caret)
      
    # Using the train() available in
    # Caret package
    model <- train(Gender ~ ., data = TrainingData, 
                   method = "svmPoly",
                   na.action = na.omit,
                   preProcess = c("scale", "center"),
                   trControl = trainControl(method = "none"),
                   tuneGrid = data.frame(degree = 1, 
                                         scale = 1, 
                                         C = 1)
    )
    model.cv <- train(Gender ~ ., data = TrainingData,
                      method = "svmPoly",
                      na.action = na.omit,
                      preProcess = c("scale", "center"),
                      trControl = trainControl(method = "cv", 
                                               number = 6),
                      tuneGrid = data.frame(degree = 1, 
                                            scale = 1,
                                            C = 1)
    )
      
    # Printing the models
    print(model)
    print(model.cv)

    
    

    Output:
    output

    ggplot2: R is most famous for its visualization library ggplot2. It provides an aesthetic set of graphics that are also interactive. The ggplot2 package is used for creating plots and for visualising data.




    # Using ggplot2
      
    # Creating a bar plot from the 
    # Data's Favorite.Color attribute
    ggplot(Data, aes(Favorite.Color)) +
      geom_bar(fill = "#0073C2FF")

    
    

    Output:
    output-graph

    randomForest: The randomForest package allows us to use the random forest algorithm easily.




    # Using randomforset
      
    # Importing the randomForest package
    library(randomForest)
      
    # Using the randomForest function 
    # From the randomForest package
    model <- randomForest(formula = Gender ~ ., 
                          data = Data)
    print(model)

    
    

    Output:
    output screen

    nnet: The nnet package uses neural networks in deep learning to create layers which help in training and predicting models. The loss (the difference between the actual value and predicted value) decreases after every iteration of training.




    # Using nnet
      
    # Importing the nnet package
    library(nnet)
      
    # Using the nnet function
    # In the nnet package 
    model <- nnet(formula = Gender ~ ., 
                  data = Data, 
                  size = 30)
    print(model)

    
    

    Output:
    output screen

    e1071: The e1071 package is used to implement the support vector machines, naive bayes algorithm and many other algorithms.




    # Using e1071
      
    # Importing the e1071 package
    library(e1071)
      
    # Using the svm function 
    # In the e1071 package
    model <- svm(formula = Gender ~ ., 
                 data = Data)
    print(model)

    
    

    Output:
    output-screen

    rpart: The rpart package is used to partition data. It is used for classification and regression tasks. The resultant model is in the form of a binary tree.




    # Using rpart
      
    # Importing the rpart package
    library(rpart)
      
    # Using the rpart function
    # To partition data
    partition <- rpart(formula = Gender~., 
                       data = Data)
    plot(partition)

    
    

    Output:
    output-screen

    dplyr: Like rpart the dplyr package is also a data manipulation package. It helps manipulate data by using functions such as filter, select, and arrange.




    # Using dplyr
      
    # Importing the dplyr package
    library(dplyr)
      
    # Using the filter function
    # From the dplyr package 
    Data %>% 
      filter(Gender == "M")

    
    

    Output:
    output-screen



    Previous Article
    Next Article

Similar Reads

Is the R programming environment capable of handling unstructured data?
Yes, the R programming environment is capable of handling unstructured data. R provides a wide range of packages and tools specifically designed for processing, analyzing, and visualizing unstructured data, such as text, images, and social media feeds. While traditionally known for its strengths in statistical analysis and structured data, R has ev
2 min read
Introduction to Machine Learning in R
The word Machine Learning was first coined by Arthur Samuel in 1959. The definition of machine learning can be defined as that machine learning gives computers the ability to learn without being explicitly programmed. Also in 1997, Tom Mitchell defined machine learning that “A computer program is said to learn from experience E with respect to some
8 min read
7 Best R Packages for Machine Learning
Machine Learning is a subset of artificial intelligence that focuses on the development of computer software or programs that access data to learn themselves and make predictions i.e. without being explicitly programmed. Machine learning consists of different sub-parts i.e. unsupervised learning, supervised learning, and reinforcement learning. It
15 min read
Machine Learning with R
Machine Learning as the name suggests is the field of study that allows computers to learn and take decisions on their own i.e. without being explicitly programmed. These decisions are based on the available data that is available through experiences or instructions. It gives the computer that makes it more similar to humans: The ability to learn.
2 min read
Implement Machine Learning With Caret In R
In today's society, technological answers to human issues are knocking on the doors of practically all fields of knowledge. Every aspect of this universe's daily operations generates data, and technology solutions base their decisions on these data-driven intuitions. In order to create a machine that learns from the obtained data and can address th
8 min read
Why Save Machine Learning Models?
Machine learning models play a pivotal role in data-driven decision-making processes. Once a model is trained on a dataset, it becomes a valuable asset that can be used for making predictions on new, unseen data. In the context of R Programming Language, saving machine learning models is a crucial step for various reasons, ranging from reusability
5 min read
How to embed my Machine-learning R code in a website
The potential of machine learning (ML) goes beyond standalone applications. When you integrate your R code into a web application you unlock its power, for real-time predictions, interactive data exploration, and improved user experiences. In this article, we will guide you through the process of incorporating your R code into a website. We'll cove
8 min read
Getting and Setting Length of the Vectors in R Programming - length() Function: Title change need
In R, the length of a vector is the number of elements it contains. Vectors can be of different types, such as numeric, character, or logical, and the length() function is a versatile way to determine the number of elements in a vector. length() function in R Programming Language is used to get or set the length of a vector (list) or other objects.
4 min read
Slot machine project using R programming
The slot machine is a game, and it comprises two steps: Generating three symbols randomly from 7 symbols and For the generated three symbols, computing score. Algorithm:The symbols used in the slot machine are:DiamondSeven3Bars2Bars1BarcherryZeroWe can take any symbol. It may depend on the choice of the individual.From the above symbols, three symb
3 min read
Deep Learning in R Programming
Deep Learning is a type of Artificial Intelligence or AI function that tries to imitate or mimic the working principle of a human brain for data processing and pattern creation for decision-making purposes. It is a subset of ML or machine learning in an AI that owns or have networks that are capable of unsupervised learning from data that are unlab
5 min read
Supervised and Unsupervised Learning in R Programming
Arthur Samuel, a pioneer in the field of artificial intelligence and computer gaming, coined the term “Machine Learning”. He defined machine learning as – “Field of study that gives computers the capability to learn without being explicitly programmed”. In a very layman manner, Machine Learning(ML) can be explained as automating and improving the l
8 min read
What are the Basic Things that must be known before Learning R Programming?
R programming is a powerful tool widely used for statistical computing, data analysis, and graphical representation. If you are new to R programming, several basic concepts and skills will make your learning process smoother and more effective. This guide will cover the fundamental things you should know before diving into R programming. 1. Underst
4 min read
Clear the Console and the Environment in R Studio
R Studio is an integrated development environment(IDE) for R. IDE is a GUI, where you can write your quotes, see the results and also see the variables that are generated during the course of programming. Clearing the Console We Clear console in R and RStudio, In some cases when you run the codes using "source" and "source with echo" your console w
2 min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
What Is the Purpose of Setting a Key in data.table in R?
In R Language the data.table package provides a powerful and efficient way to handle and manipulate large datasets. One of its unique and highly useful features is the ability to set a "key" on a data.table. Setting a key can significantly enhance the performance of various data operations such as sorting, merging, and subsetting. This article expl
4 min read
Support Vector Machine Classifier Implementation in R with Caret package
One of the most crucial aspects of machine learning that most data scientists run against in their careers is the classification problem. The goal of a classification algorithm is to foretell whether a particular activity will take place or not. Depending on the data available, classification algorithms strive to provide answers to questions like w
7 min read
Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
tidyr Package in R Programming
Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the proc
14 min read
Get Exclusive Elements between Two Objects in R Programming - setdiff() Function
setdiff() function in R Programming Language is used to find the elements which are in the first Object but not in the second Object. Syntax: setdiff(x, y) Parameters: x and y: Objects with sequence of itemsR - setdiff() Function ExampleExample 1: Apply setdiff to Numeric Vectors in R Language C/C++ Code # R program to illustrate # the use of setdi
2 min read
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0("0", vec) or sprintf("%0d", vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Exa
1 min read
Clustering in R Programming
Clustering in R Programming Language is an unsupervised learning technique in which the data set is partitioned into several groups called clusters based on their similarity. Several clusters of data are produced after the segmentation of data. All the objects in a cluster share common characteristics. During data mining and analysis, clustering is
6 min read
Compute Variance and Standard Deviation of a value in R Programming - var() and sd() Function
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value. Syntax: var(x) Parameters: x : numeric vector Example 1: Computing variance of a vector # R program to illustrate # variance of vector # Create example vector x &lt;- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in
1 min read
Compute Density of the Distribution Function in R Programming - dunif() Function
dunif() function in R Language is used to provide the density of the distribution function. Syntax: dunif(x, min = 0, max = 1, log = FALSE) Parameters: x: represents vector min, max: represents lower and upper limits of the distribution log: represents logical value for probabilities Example 1: # Create vector of random deviation u &lt;- runif(20)
1 min read
Compute Randomly Drawn F Density in R Programming - rf() Function
rf() function in R Language is used to compute random density for F Distribution. Syntax: rf(N, df1, df2) Parameters: N: Sample Size df: Degree of Freedom Example 1: # R Program to compute random values # of F Density # Setting seed for # random number generation set.seed(1000) # Set sample size N &lt;- 20 # Calling rf() Function y &lt;- rf(N, df1
1 min read
Data Handling in R Programming
R Programming Language is used for statistics and data analytics purposes. Importing and exporting of data is often used in all these applications of R programming. R language has the ability to read different types of files such as comma-separated values (CSV) files, text files, excel sheets and files, SPSS files, SAS files, etc. R allows its user
5 min read
Return a Matrix with Lower Triangle as TRUE values in R Programming - lower.tri() Function
lower.tri() function in R Language is used to return a matrix of logical values with lower triangle as TRUE. Syntax: lower.tri(x, diag) Parameters: x: Matrix object diag: Boolean value to include diagonal Example 1: # R program to print the # lower triangle of a matrix # Creating a matrix mat &lt;- matrix(c(1:9), 3, 3, byrow = T) # Calling lower.tr
1 min read
Print the Value of an Object in R Programming - identity() Function
identity() function in R Language is used to print the value of the object which is passed to it as argument. Syntax: identity(x) Parameters: x: An Object Example 1: # R program to print # the value of an object # Creating a vector x &lt;- c(1, 2, 3, 4) # Creating a list list1 &lt;- list(letters[1:6]) # Calling the identity function identity(x) ide
1 min read
Check if Two Objects are Equal in R Programming - setequal() Function
setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not. Syntax: setequal(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of setequal(
1 min read
Random Forest with Parallel Computing in R Programming
Random Forest in R Programming is basically a bagging technique. From the name we can clearly interpret that this algorithm basically creates the forest with a lot of trees. It is a supervised classification algorithm. In a general scenario, if we have a greater number of trees in a forest it gives the best aesthetic appeal to all and is counted as
4 min read
R - Object Oriented Programming
In this article, we will discuss Object-Oriented Programming (OOPs) in R Programming Language. We will discuss the S3 and S4 classes, the inheritance in these classes, and the methods provided by these classes. OOPs in R Programming Language:In R programming, OOPs in R provide classes and objects as its key tools to reduce and manage the complexity
7 min read