The Wayback Machine - https://web.archive.org/web/20240828110756/https://www.geeksforgeeks.org/conversion-functions-in-r-programming/
Open In App

Conversion Functions in R Programming

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

Sometimes to analyze data using R, we need to convert data into another data type. As we know R has the following data types Numeric, Integer, Logical, Character, etc. similarly R has various conversion functions that are used to convert the data type.

In R, Conversion Function are of two types:

  • Conversion Functions for Data Types
  • Conversion Functions for Data Structures

Conversion Functions For Data Types

There are various conversion functions available for Data Types. These are:

  • as.numeric()

    Decimal value known numeric values in R. It is the default data type for real numbers in R. In R as.numeric() converts any values into numeric values.
    Syntax:

    // Conversion into numeric data type
    as.numeric(x)
    

    Example:




    # A simple R program to convert 
    # character data type into numeric data type
    x<-c('1', '2', '3')
      
    # Print x
    print(x)
      
    # Print the type of x
    print(typeof(x))
      
    # Conversion into numeric data type
    y<-as.numeric(x)
      
    # print the type of y
    print(typeof(y))

    
    

    Output:

    [1] "1" "2" "3"
    [1] "character"
    [1] "double"
    
  • as.integer()
    In R, Integer data type is a collection of all integers. In order to create an integer variable in R and convert any data type in to Integer we use as.integer() function.
    Syntax:

    // Conversion of any data type into Integer data type
    as.integer(x)
    

    Example:




    # A simple R program to convert
    # numeric data type into integer data type
    x<-c(1.3, 5.6, 55.6)
      
    # Print x
    print(x)
      
    # Print type of x
    print(typeof(x))
      
    # Conversion into integer data type
    y<-as.integer(x)
      
    # Print y
    print(y)
      
    # Print type of y
    print(typeof(y))

    
    

    Output:

    [1]  1.3  5.6 55.6
    [1] "double"
    [1]  1  5 55
    [1] "integer"
    
  • as.character()
    In R, character data is used to store character value and string. To create an character variable in R, we invoke the as.character() function and also if we want to convert any data type in to character we use as.character() function.
    Syntax:

    // Conversion of any data type into character data type
    as.character(x)
    

    Example:




    x<-c(1.3, 5.6, 55.6)
      
    # Print x
    print(x)
      
    # Print type of x
    print(typeof(x))
      
    # Conversion into character data type
    y<-as.character(x)
      
    # Print y
    print(y)
      
    # Print type of y
    print(typeof(y))

    
    

    Output:

    [1]  1.3  5.6 55.6
    [1] "double"
    [1] "1.3"  "5.6"  "55.6"
    [1] "character"
    
  • as.logical()
    Logical value is created to compare variables which return either true or false.To compare variables and to convert any value in to true or false, R uses as.logical() function.
    Syntax:

    // Conversion of any data type into logical data type
    as.logical(x)
    

    Example:




    x = 3
    y = 8
      
    # Conversion in to logical value
    result<-as.logical(x>y)
      
    # Print result
    print(result)

    
    

    Output:

    [1] FALSE
    
  • as.date()
    In R as.date() function is used to convert string into date format.

    Syntax:

    // Print string into date format
    as.date(variable, "%m/%d/%y")
    

    Example:




    dates <- c("02/27/92", "02/27/92", 
               "01/14/92", "02/28/92", 
               "02/01/92")
      
    # Conversion into date format
    result<-as.Date(dates, "%m/%d/%y")
      
    # Print result
    print(result)

    
    

    Output:

    [1] "1992-02-27" "1992-02-27" "1992-01-14" "1992-02-28" "1992-02-01"
    

Conversion Functions For Data Structure

There are various conversion functions available for Data Structure. These are:

  • as.data.frame()
    Data Frame is used to store data tables. Which is list of vectors of equal length. In R, sometimes to analyse data we need to convert list of vector into data.frame. So for this R uses as.data.frame() function to convert list of vector into data frame.
    Syntax:

    // Conversion of any data structure into data frame
    as.data.frame(x)
    

    Example:




    x<- list( c('a', 'b', 'c'),
    c('e', 'f', 'g'), c('h', 'i', 'j'))
      
    # Print x
    print(x)
      
    # Conversion in to data frame
    y<-as.data.frame(x)
      
    # Print y
    print(y)

    
    

    Output:

    [[1]]
    [1] "a" "b" "c"
    
    [[2]]
    [1] "e" "f" "g"
    
    [[3]]
    [1] "h" "i" "j"
    
      c..a....b....c.. c..e....f....g.. c..h....i....j..
    1                a                e                h
    2                b                f                i
    3                c                g                j
    
  • as.vector()
    R has a function as.vector() which is used to convert a distributed matrix into a non-distributed vector. Vector generates a vector of the given length and mode.
    Syntax:

    // Conversion of any data structure into vector
    as.vector(x)
    

    Example:




    x<-c(a=1, b=2)
      
    # Print x
    print(x)
      
    # Conversion into vector
    y<-as.vector(x)
      
    # Print y
    print(y)

    
    

    Output:

    a b 
    1 2 
    [1] 1 2
    
  • as.matrix()
    In R, there is a function as.matrix() which is used to convert a data.table into a matrix, optionally using one of the columns in the data.table as the matrix row names.
    Syntax:

    // Conversion into matrix
    as.matrix(x)
    

    Example:




    # Importing library
    library(data.table)
    x <- data.table(A = letters[1:5], X = 1:5, Y = 6:10)
      
    # Print x
    print(x)
      
    # Conversion into matrix
    z<-as.matrix(x)
      
    # Print z
    print(z)

    
    

    Output:

       A X  Y
    1: a 1  6
    2: b 2  7
    3: c 3  8
    4: d 4  9
    5: e 5 10
         A   X   Y   
    [1,] "a" "1" " 6"
    [2,] "b" "2" " 7"
    [3,] "c" "3" " 8"
    [4,] "d" "4" " 9"
    [5,] "e" "5" "10"
    


Previous Article
Next Article

Similar Reads

Recursive Functions in R Programming
Recursion, in the simplest terms, is a type of looping technique. It exploits the basic working of functions in R. Recursive Function in R: Recursion is when the function calls itself. This forms a loop, where every time the function is called, it calls itself again and again and this technique is known as recursion. Since the loops increase the me
4 min read
Logarithmic and Power Functions in R Programming
Logarithm and Power are two very important mathematical functions that help in the calculation of data that is growing exponentially with time. First is the Logarithm, to which the general way to calculate the logarithm of the value in the base is with the log() function which takes two arguments as value and base, by default it computes the natura
3 min read
Poisson Functions in R Programming
The Poisson distribution represents the probability of a provided number of cases happening in a set period of space or time if these cases happen with an identified constant mean rate (free of the period since the ultimate event). Poisson distribution has been named after Siméon Denis Poisson(French Mathematician). Many probability distributions c
3 min read
Applying User-defined Functions on Factor Levels of Dataset in R Programming - by() Function
by() function in R programming is an object-oriented wrapper function which performs the provided function on factor levels of the data set passed in the arguments of function call. Syntax: by(data, INDICES, FUN) Parameters: data: represents the dataset INDICES: represents the factor list of dataset FUN: represents the function to be performed on f
1 min read
Performing Logarithmic Computations in R Programming - log(), log10(), log1p(), and log2() Functions
log() function in R Language returns the natural logarithm (base-e logarithm) of the argument passed in the parameter. Syntax: log(x) Parameter: x: Specified value. Returns: It returns the natural logarithm of the specified value, infinity for 0 and NaN for the negative value. Example 1: # R program to calculate log value print(log(1)) print(log(30
3 min read
Get Summary of Results produced by Functions in R Programming - summary() Function
summary() function in R Language is a generic function used to produce result summaries of the results of various model fitting functions. Syntax: summary(object, maxsum) Parameters: object: R object maxsum: integer value which indicates how many levels should be shown for factors Example 1: # R program to illustrate # summary function # Initializi
2 min read
Compute the Parallel Minima and Maxima between Vectors in R Programming - pmin() and pmax() Functions
pmin() function in R Language is used to return the parallel minima of the input vectors. Syntax: pmin(x1, x2) Parameters: x1: vector one x2: vector two Example 1: # R program to illustrate # pmin() function # First example vector x1 &lt;- c(2, 9, 5, 7, 1, 8) # Second example vector x2 &lt;- c(0, 7, 2, 3, 9, 6) # Application of pmin() in R pmin(x1,
1 min read
Compute Beta Distribution in R Programming - dbeta(), pbeta(), qbeta(), and rbeta() Functions
Beta Distribution in R Language is defined as property which represents the possible values of probability. This article is an illustration of dbeta, pbeta, qbeta, and rbeta functions of Beta Distribution. dbeta() Function It is defined as Beta Density function and is used to create beta density value corresponding to the vector of quantiles. Synta
2 min read
Types of Functions in R Programming
A function is a set of statements orchestrated together to perform a specific operation. A function is an object so the interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions. The function in turn performs the task and returns control to the interpreter as well as a
6 min read
Exponential Distribution in R Programming - dexp(), pexp(), qexp(), and rexp() Functions
The exponential distribution in R Language is the probability distribution of the time between events in a Poisson point process, i.e., a process in which events occur continuously and independently at a constant average rate. It is a particular case of the gamma distribution. In R Programming Language, there are 4 built-in functions to generate ex
2 min read
Gamma Distribution in R Programming - dgamma(), pgamma(), qgamma(), and rgamma() Functions
The Gamma distribution in R Programming Language is defined as a two-parameter family of continuous probability distributions which is used in exponential distribution, Erlang distribution, and chi-squared distribution. This article is about the implementation of functions of the gamma distribution. dgamma() Function The dgamma() function is used t
2 min read
Functions in R Programming
A function accepts input arguments and produces the output by executing valid R commands that are inside the function. Functions are useful when you want to perform a certain task multiple times. In R Programming Language when you are creating a function the function name and the file in which you are creating the function need not be the same and
8 min read
Poisson Functions in R Programming
The Poisson distribution represents the probability of a provided number of cases happening in a set period of space or time if these cases happen with an identified constant mean rate (free of the period since the ultimate event). Poisson distribution has been named after Siméon Denis Poisson(French Mathematician). Many probability distributions c
3 min read
Case conversion of a String in R Language - toupper(), tolower(), casefold() and cartr() Function
In this article, we are going to see case conversion of a string in R Programming Language. R - toupper() toupper() function in R Language is used to convert the lowercase letters to uppercase. Syntax: toupper(x) Parameters: x: character vector Example: C/C++ Code # R program to illustrate # uppercase of vectors # Create example character string x
2 min read
Data Type Conversion in R
Prerequisite: Data Types in the R Data Type conversion is the process of converting one type of data to another type of data. R Programming Language has only 3 data types: Numeric, Logical, Character. In this article, we are going to see how to convert the data type in the R Programming language Since R is a weakly typed language or dynamically typ
5 min read
10 Best Conversion Rate Optimization Tools in 2024
In the modern, hectic world of the internet, each click on your page counts. Converting visitors into devoted clients is essential, regardless of whether you're sharing your ideas, selling goods, or providing services. But how is that accomplished? This is where conversion rate optimization (CRO) becomes useful. Imagine having a hidden toolbox full
12 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
How to combine Groupby and Multiple Aggregate Functions in Pandas?
Pandas is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. It is an open-source library that is built on top of NumPy library. Groupby() Pandas dataframe.groupby() function is used to split the data in dataframe int
1 min read
Union() & union_all() functions in Dplyr package in R
In this article, we will discuss union() and union_all() functions using Dplyr package in the R programming language. Dataframes in use: Example: R program to create data frames with college student data and display them C/C++ Code # create dataframe1 with college # 1 data data1=data.frame(id=c(1,2,3,4,5), name=c('sravan','ojaswi','bobby', 'gnanesh
2 min read
Specify Multiple Arguments in apply Functions in R
In this article, we will discuss how to specify multiple arguments in apply functions in the R programming language. apply() function is used to apply conditions to get the resultant data like mean of data, the sum of data, etc. Syntax: apply(data, margin, function, na.rm = TRUE) where, data is the input dataframemargin is used to specify the width
2 min read
Interpolation Functions in R
In this article, we will be looking towards the approx() and the aproxfun() interpolation function with working examples in the R Programming language. Approx() and Approxfun() interpolation function These functions return a list of points that linearly interpolates given data points, or a function performing the linear (or constant) interpolation.
5 min read
as.double() and is.double() Functions in R
In this article, we will discuss about as.double() and is.double() functions in R Programming Language. as.double() Method in R as.double is used to convert an integer to double. Syntax: as.double(input_values) Both will take values as input. Example: In this example, we will a vector with 5 elements and convert to double using as.double() C/C++ Co
1 min read
cumall(), cumany() & cummean() R Functions of dplyr Package
In this article, we will discuss about cumall(), cummany(), and cummean() functions in R Programming Language. Which are available in dplyr() package. We have to install and load dplyr package. Install - install.packages("dplyr") Load - library("dplyr")cumall() This function will check whether the first element is TRUE. if yes, then it will return
3 min read
apropos() and find() Functions in R?
In this article, we will be discussing the aprops() and the find() functions with these working examples in the R programming language. Functions definitions:apropos() function: This function returns a character vector giving the names of objects in the search list matching what.find() function: This returns where objects of a given name can be fou
2 min read
Model predictions to find the best model fit using the juice() and bake() functions in R
The juice() function in R Programming Language is used to extract the data from a recipe object. It is a part of the recipes package. juice() FunctionA recipe object is a data structure that represents a pre-processing pipeline. It can be used to transform data in a consistent way. The juice() function can be used to extract the data from a recipe
11 min read
Apply a Function (or functions) across Multiple Columns using dplyr in R
Data processing and manipulation are one of the core tasks in data science and machine learning. R Programming Language is one of the widely used programming languages for data science, and dplyr package is one of the most popular packages in R for data manipulation. In this article, we will learn how to apply a function (or functions) across multi
10 min read
Pure Functions
A function is called pure function if it always returns the same result for same argument values and it has no side effects like modifying an argument (or global variable) or outputting something. The only result of calling a pure function is the return value. Examples of pure functions are strlen(), pow(), sqrt() etc. Examples of impure functions
2 min read
How to Handle Invalid Argument Error in R Functions
Handling invalid argument errors in R functions involves implementing proper input validation and providing informative error messages to users. In this guide, we'll explore common practices for handling invalid argument errors, along with examples in R Programming Language. Types of errors for Invalid Argument Error in R FunctionsMissing Argument
3 min read
saveRDS() and readRDS() Functions in R
The saveRDS function is a serialization interface for single objects and it is usually used with the readRDS function. Both saveRDS and readRDS are used for saving individual R Programming Language objects to a connection usually called a file and to restore these objects under different names. saveRDS() and readRDS() Functions in RAll the interfac
7 min read
Aggregate data using custom functions using R
In this article, we will explore various methods to aggregate data using custom functions by using the R Programming Language. What is a custom function?Custom functions are an essential part of R programming, which allows users to create reusable blocks of code tailored to their specific needs. These functions encapsulate a series of operations, m
5 min read