Working with Data Types in R

Working with Data Types in R

 

Introduction

As a powerful statistical programming language, R has a wide variety of data types and data structures. To be proficient in R, it is important to understand these data types and learn how to work with them.

In this guide, you will learn concepts and techniques for working with data types in R.

Data Types

R works with several data types. Some of the basic ones include:

  • Characters: Text (or string) values are called characters, as shown in the example below. If we want to confirm its type, we can use the class() function. In fact, R provides many functions like class() that can be used to examine features of objects, such as typeof(), length(), and attributes().


t = "data types"
class(t)

Output:


[1] "character"
  • Numeric: Decimal values like 2.3 is called numeric in R. It is the default computational data type.

N = 2.3
class(N)
 

Output:


[1] "numeric"

Note that the variable ‘N’ is stored as a numeric value and not as an integer. This can be checked using the is.integer() function, as shown below:


is.integer(N)

Output:


[1] FALSE
  • Integers: If we want to create an integer variable, we can use the integer function. Also, all integers are numeric, but the reverse is not true.

i = as.integer(3)
is.integer(i)

is.numeric(i)

Output:


[1] TRUE

[1] TRUE
  • Logical: Logical values are often created by comparing two or more variables. These are denoted by Boolean values, TRUE or FALSE.

x = 100
y = 56
x < y

Output:


[1] FALSE 
  • Complex: The complex variable is defined by the imaginary value i.


z = 3 + 2i 
class(z)

Output:


[1] "complex"

The above examples are the basic data types in R. However, this is not an exhaustive list of classes. R also has many data structures, as discussed in the subsequent sections.

Data Structures

Vectors

A vector is the most common data structure in R. It is a sequence of elements of the same data type. The vector() function can be used to create a vector. The default mode is logical, but we can use constructors such as character(), numeric(), etc., to create a vector of a specific type.

The lines of code below construct a numeric and a logical vector, respectively. A vector can also contain strings, as indicated by the vector ‘s’.


n <- c(1,2,5.3,6,-2,4) 
l <- c(TRUE,TRUE,TRUE,FALSE,TRUE,FALSE) 
s = c("USA", "UK", "AFRICA", "INDIA", "CHINA") 

class(n)
class(l)
class(s)

Output:


[1] "numeric"

[1] "list"

[1] "character"

It is also possible to perform several operations on the vectors, such as combining vectors and vector mathematics. For example, the first line of code below combines the vectors ‘n’ and ‘l’, while the second line prints the elements of the new vector. You can check the length of the resultant vector using the length function, as shown in the third command. The fourth line checks the data type, and the resulting vector is of ‘character’ type. This is called value coercion in vector combinations.


comb = c(n, s)
comb

length(comb)
class(comb

Output:


[1] "1"      "2"      "5.3"    "6"      "-2"     "4"      "USA"    "UK"    
 [9] "AFRICA" "INDIA"  "CHINA"


[1] 11


[1] "character"

It is also possible to perform mathematical operations on vectors, as in the lines of code below.


x = c(5, 3, 4) 
y = c(1, 2, 3)

#Arithmetic Operations
5 * x
x-y
x+y
x/y

Output:


[1] 25 15 20

[1] 4 1 1

[1] 6 5 7

[1] 5.000000 1.500000 1.333333 

Matrices

In R, matrices are an extension of numeric or character vectors. All columns in a matrix must have the same mode and the same length. Also, similar to atomic vectors, the elements of a matrix must be of the same data type. The general representation of a matrix is shown in the line of code below.

The arguments nrow and ncol denote the number of rows and columns, respectively. The argument byrow = TRUE indicates that the matrix should be filled by the rows.


m = matrix(c(20, 45, 33, 19, 52, 37), nrow=2, ncol=3, byrow = TRUE)    
print(m)

Output:


     [,1] [,2] [,3]
[1,]   20   45   33
[2,]   19   52   37

It is possible to identify the rows, columns, or elements of a matrix using subscripts. For example, the element at the second row and second column can be accessed using the following command.


m[2, 2]

Output:


[1] 52

Lists

A list is a generic vector containing a collection of objects (or components). The advantage of a list is that it allows you to store a variety of objects that may be unrelated under one name.

The lines of code below create a list containing three vectors: name, place, and age in years.


name = c("abhi", "ansh", "ajay") 
place = c("delhi", "mumbai", "pune") 
age = c(TRUE, FALSE, TRUE, FALSE, FALSE) 

l = list(name, place, age)   
print(l)

Output:


[[1]]
[1] "abhi" "ansh" "ajay"

[[2]]
[1] "delhi"  "mumbai" "pune"  

[[3]]
[1]  TRUE FALSE  TRUE FALSE FALSE

It is also possible to slice a list using the single square bracket “ ” operator.


l[2] 

l[c(2, 3)]

Output:


[[1]]
[1] "delhi"  "mumbai" "pune"  

[[2]]
[1]  TRUE FALSE  TRUE FALSE FALSE

Data Frame

Data frame is perhaps the most important data type in R. It is in fact the de-facto data structure for most tabular data and is used extensively in data science. In simple terms, it is a special type of list where all the elements are of equal length.

Data frames are often imported into R using the read.csv() and read.table() functions. You can also create a new data frame with the data.frame() function, as in the line of code below.


df <- data.frame(rollnum = seq(1:10), h1 = 15:24, h2 = 81:90)
df

Output:


| rollnum 	| h1 	| h2 	|
|---------	|----	|----	|
| 1       	| 15 	| 81 	|
| 2       	| 16 	| 82 	|
| 3       	| 17 	| 83 	|
| 4       	| 18 	| 84 	|
| 5       	| 19 	| 85 	|
| 6       	| 20 	| 86 	|
| 7       	| 21 	| 87 	|
| 8       	| 22 	| 88 	|
| 9       	| 23 	| 89 	|
| 10      	| 24 	| 90 	|

Conclusion

In this guide, you have learned about different types and structures of data, including concepts and techniques for creating and working with data types in R.

 

Python Example for Beginners

Two Machine Learning Fields

There are two sides to machine learning:

  • Practical Machine Learning:This is about querying databases, cleaning data, writing scripts to transform data and gluing algorithm and libraries together and writing custom code to squeeze reliable answers from data to satisfy difficult and ill defined questions. It’s the mess of reality.
  • Theoretical Machine Learning: This is about math and abstraction and idealized scenarios and limits and beauty and informing what is possible. It is a whole lot neater and cleaner and removed from the mess of reality.

 

Data Science Resources: Data Science Recipes and Applied Machine Learning Recipes

Introduction to Applied Machine Learning & Data Science for Beginners, Business Analysts, Students, Researchers and Freelancers with Python & R Codes @ Western Australian Center for Applied Machine Learning & Data Science (WACAMLDS) !!!

Latest end-to-end Learn by Coding Recipes in Project-Based Learning:

Applied Statistics with R for Beginners and Business Professionals

Data Science and Machine Learning Projects in Python: Tabular Data Analytics

Data Science and Machine Learning Projects in R: Tabular Data Analytics

Python Machine Learning & Data Science Recipes: Learn by Coding

R Machine Learning & Data Science Recipes: Learn by Coding

Comparing Different Machine Learning Algorithms in Python for Classification (FREE)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.  

Google –> SETScholars