Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
Data Type Conversion in R
Next article icon

Data Type Conversion in R

Last Updated : 21 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 typed language, R language automatically creates data types based on the values assigned to the variable. We see a glimpse of this in the code below:

R
# value assignment name <- "GeeksforGeeks" age <- 20 pwd <- FALSE  # type checking typeof(name) typeof(age) typeof(pwd) 

Output:

[1] "character"  [1] "double"  [1] "logical"

We have used typeof(value) function to check the type of the values assigned to the variables in the above code.

Data Type Conversion in R

Numeric or Character to Logical type:

Any numeric value which is not 0, on conversion to Logical type gets converted to TRUE. Here "20" is a non-zero numeric value. Hence, it gets converted to TRUE.  

"FALSE" is a character type which on conversion becomes FALSE of logical type. The double quotes are removed on conversion from character type to Logical type.

Syntax: as.logical(value)

Example:

R
# value assignment age <- 20 pwd <- "FALSE"  # Converting type as.logical(age) as.logical(pwd) 

Output:

[1] TRUE  [1] FALSE

Numeric or Logical to Character type:

Any character type values are always enclosed within double quotes(" ").  Hence, the conversion of 20 of numeric type gets converted into "20" of character type. Similarly, converting the FALSE of logical type into character type gives us "FALSE".

Syntax: as.character(value)

Example:

R
# value assignment age <- 20 pwd <- FALSE  # Converting type as.character(age) as.character(pwd) 

Output:

[1] "20"  [1] "FALSE"

Character or Logical to Numeric type:

Syntax: as.numeric(value)

 "20" of character type on being converted to numeric type becomes 20, just the double quotes got removed. Conversion of Logical type to Numeric, FALSE-> 0 and TRUE-> 1.

Example:

R
# value assignment age <- "20" pwd <- FALSE  # Converting type as.numeric(age) as.numeric(pwd) 

Output:

[1] 20  [1] 0

Vectors to Matrix:

In the code below, we have converted 2 sample vectors into a single matrix by using the syntax below. The elements of the vectors are filled in Row major order.

Syntax: rbind(vector1, vector2, vector3.....vectorN)

We have converted 2 sample vectors into a single matrix by using the syntax below. The elements of the vectors are filled in Column major order.

Syntax:  cbind(vector1, vector2, vector3.....vectorN)

Example:

R
# sample vectors vector1 <- c('red','green',"blue","yellow") vector2 <- c(1,2,3,4)  print("Row Major Order") rbind(vector1,vector2) print("Column Major Order") cbind(vector1,vector2) 

Output:

[1] "Row Major Order"          [,1]  [,2]    [,3]   [,4]      vector1 "red" "green" "blue" "yellow"  vector2 "1"   "2"     "3"    "4"         [1] "Column Major Order"       vector1  vector2  [1,] "red"    "1"      [2,] "green"  "2"      [3,] "blue"   "3"      [4,] "yellow" "4"    

Vectors to Dataframe:

In the code below, on the conversion of our sample vectors into dataframe, elements are filled in the column-major order. The first vector becomes the 1st column, the second vector became the 2nd column.

Syntax: data.frame(vector1, vector2, vector3.....vectorN)  

Example:

R
# sample vectors vector1 <- c('red', 'green', "blue", "yellow") vector2 <- c(1, 2, 3, 4)  data.frame(vector1, vector2)   

Output:

 vector1 vector2  1     red       1  2   green       2  3    blue       3  4  yellow       4

Matrix to Vector:

In the code below, the sample matrix is containing elements from 1 to 6, we have specified nrows=2 which means our sample matrix will be containing 2 rows, then we have used the syntax below which converts the matrix into one long vector. The elements of the matrix are accessed in column-major order. 

Syntax: as.vector(matrix_name)

Example:

R
# sample matrix mat<- matrix(c(1:6), nrow = 2) print("Sample Matrix") mat  print("After conversion into vector") as.vector(mat) 

Output:

[1] "Sample Matrix"       [,1] [,2] [,3]  [1,]    1    3    5  [2,]    2    4    6    [1] "After conversion into vector"  [1] 1 2 3 4 5 6

Matrix to Dataframe:

In the code below, the sample matrix is containing elements from 1 to 6, we have specified nrows=2 which means our sample matrix will be containing 2 rows, then we have used the syntax below which converts the matrix into a dataframe. The elements of the matrix are accessed in column-major order. 

Syntax: as.data.frame(matrix_name)

Example:

R
# sample matrix mat<- matrix(c(1:6), nrow = 2) print("Sample Matrix") mat  print("After conversion into Dataframe") as.data.frame(mat) 

Output:

[1] "Sample Matrix"       [,1] [,2] [,3]  [1,]    1    3    5  [2,]    2    4    6    [1] "After conversion into Dataframe"    V1 V2 V3  1  1  3  5  2  2  4  6

Dataframe to Matrix:

In the code below, we have created a sample dataframe containing elements of different types, then we have used the syntax below which converts the dataframe into a matrix of character type, which means each element of the matrix is of character type.

Syntax: as.matrix(dataframe_name)

Example:

R
# sample dataframe df <- data.frame(    serial = c (1:5),     name = c("Welcome","to","Geeks","for","Geeks"),    stipend = c(2000,3000.5,5000,4000,500.2),     stringsAsFactors = FALSE)  print("Sample Dataframe") df  print("After conversion into Matrix") as.matrix(df) 

Output:

[1] "Sample Dataframe"    serial    name stipend  1      1 Welcome  2000.0  2      2      to  3000.5  3      3   Geeks  5000.0  4      4     for  4000.0  5      5   Geeks   500.2    [1] "After conversion into Matrix"       serial name      stipend   [1,] "1"    "Welcome" "2000.0"  [2,] "2"    "to"      "3000.5"  [3,] "3"    "Geeks"   "5000.0"  [4,] "4"    "for"     "4000.0"  [5,] "5"    "Geeks"   " 500.2"

Next Article
Data Type Conversion in R

S

sudhanshublaze
Improve
Article Tags :
  • Data Science
  • Machine Learning
  • R Language
  • AI-ML-DS
  • R Data-types
Practice Tags :
  • Machine Learning

Similar Reads

    Data Type Conversion in MATLAB
    Data Types in MATLAB is the upheld information organizes that are utilized for calculation. MATLAB is a well-known numerical and factual information investigation instrument that has a large number of elements for calculation. The different kinds of data type MATLAB supports are numeric types, chara
    3 min read
    Convert DataFrame to vector in R
    In this article, we will discuss how a dataframe can be converted to a vector in R. For the Conversion of dataframe into a vector, we can simply pass the dataframe column name as [[index]]. Approach: We are taking a column in the dataframe and passing it into another variable by the selection method
    2 min read
    Convert Tibble to Data Frame in R
    Tibbles are a type of data frame in R Programming Language that has an enhanced print method, making it easier to display data. However, in some situations, we may need to convert a tibble to a data frame. So, in this article, we will explore some approaches to convert tibbles to data frames. Tibble
    4 min read
    How to Check Data Type in R?
    R programming has data types that play a very significant role in determining how data is documented, modified, and analyzed. Knowing the data type of an object is an essential part of most data analysis and programming. The current article delivers a step-by-step guide that will familiarize you wit
    4 min read
    Convert dataframe to data.table in R
    In this article, we will discuss how to convert dataframe to data.table in R Programming Language. data.table is an R package that provides an enhanced version of dataframe. Characteristics of data.table :  data.table doesn’t set or use row namesrow numbers are printed with a : for better readabilit
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences