Data Frames:
R Programming Language is an open-source programming language that is widely used as a
statistical software and data analysis tool. Data Frames in R Language are generic data objects
of R that are used to store tabular data. Data frames can also be interpreted as matrices where each
column of a matrix can be of different data types. R DataFrame is made up of three principal
components, the data, rows, and columns.
R-Data Frames
Create Dataframe in R Programming Language
To create an R data frame use [Link]() command and then pass each of the vectors you have
created as arguments to the function.
Example:
# R program to create dataframe
# creating a data frame
[Link] <- [Link](
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)
# print the data frame
print([Link])
Statistical Computing & R Programming Page 1
Output:
friend id friend_name
1 1 Sachin
2 2 Sourav
3 3 Dravid
4 4 Sehwag
5 5 Dhoni
(The stringsAsFactors is an argument of the “[Link]()” function. It is a logical argument
suggesting whether the strings in a data frame should be treated as factor variables or just plain
strings. By default, stringAsFactors=TRUE in older version of R, but in never versions, it is set to
FALSE)
Get the Structure of the R-Data Frame
One can get the structure of the R data frame using str() function in R. It can display even the
internal structure of large lists which are nested. It provides one-liner output for the basic R objects
letting the user know about the object and its constituents(ಘಟಕಗಳು).
Example:
# R program to get the
# structure of the data frame
# creating a data frame
[Link] <- [Link](
friend _id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
)
# using str()
print(str([Link]))
Output:
'[Link]': 5 obs. of 2 variables:
$ friend_id int 12345
$ friend_name: chr "Sachin" "Sourav" "Dravid" "Sehwag" ...
NULL
Statistical Computing & R Programming Page 2
Summary of data in the R data frame
In the R data frame, the statistical summary and nature of the data can be obtained by applying
summary() function. It is a generic function used to produce result summaries of the results of
various model fitting functions. The function invokes particular methods which depend on the
class of the first argument.
Example:
# R program to get the
# summary of the data frame
# creating a data frame
[Link] <- [Link](
friend_id = c(1:5),
friend_name = c("Sachin", "Sourav",
"Dravid", "Sehwag",
"Dhoni"),
stringsAsFactors = FALSE
# using summary()
print(summary([Link]))
Output:
friend id friend_name
Min. :1 Length:5
1st Qu.:2 Class :Character
Median :3 Mode :character
Mean :3
3rd Qu.:4
Max. :5
Statistical Computing & R Programming Page 3
Special Values:
R comes with some special values. Some of the special values in R are NA, Inf, -Inf, and
NaN.
NA
In R, the NA values are used to represent missing values. (NA stands for “not available.”) You
may encounter NA values in text loaded into R (to represent missing values) or in data loaded
from databases (to replace NULL values).
If you expand the size of a vector (or matrix or array) beyond the size where values were
defined, the new spaces will have the value NA:
v <- c(1,2,3)
v
[1] 1 2 3
length(v) <-4
v
[1] 1 2 3 NA
Inf and -Inf
If a computation results in a number that is too big, R will return Inf for a positive number
and -Inf for a negative number (meaning positive and negative infinity, respectively):
2 ^ 1024
[1] Inf
- 2 ^ 1024
[1] -Inf
NaN
Sometimes, a computation will produce a result that makes little sense. In these cases, R will
often return NaN (meaning “not a number”):
Inf - Inf
[1] NaN
0/0
[1] NaN
Statistical Computing & R Programming Page 4
R - Handling Missing Values
Missing values are practical in life. For example, some cells in spreadsheets are empty. If an
insensible or impossible arithmetic operation is tried then NAs occur.
Dealing Missing Values in R
Missing Values in R, are handled with the use of some pre-defined functions:
[Link]() Function for Finding Missing values:
A logical vector is returned by this function that indicates all the NA values present. It returns a
Boolean value. If NA is present in a vector, it returns TRUE else FALSE.
Example:
x<- c(NA, 3, 4, NA, NA, NA)
[Link](x)
Output:
TRUE FALSE FALSE TRUE TRUE TRUE
Properties of Missing Values:
For testing objects that are NA use [Link]()
For testing objects that are NaN use [Link]()
The creation of a vector with one or multiple NAs is also possible.
Examples:
x<- c(NA, 3, 4, NA, NA, NA)
x
Output:
NA 3 4 NA NA NA
Removing NA or NaN values
There are two ways to remove missing values:
Extracting values except for NA or NaN values:
Example 1:
x <- c(1, 2, NA, 3, NA, 4)
d <- [Link](x)
x[! d]
Output:
1234
Example 2:
Statistical Computing & R Programming Page 5
x <- c(1, 2, 0/0, 3, NA, 4, 0/0)
x
x[! [Link](x)]
Output:
1 2 NaN 3 NA 4 NaN
1234
Classes in R Programming
Classes and Objects are basic concepts of Object-Oriented Programming that revolve around the
real-life entities. Everything in R is an object. An object is simply a data structure that has some
methods and attributes. A class is just a blueprint or a sketch of these objects. It represents the set
of properties or methods that are common to all objects of one type.
Unlike most other programming languages, R has a three-class system. These are S3, S4, and
Reference Classes.
S3 Class
S3 is the simplest yet the most popular OOP system and it lacks formal definition and structure.
An object of this type can be created by just adding an attribute to it. Following is an example to
make things more clear:
Example:
# create a list with required components
movieList <- list(name = "Iron man", leadActor = "Robert Downey Jr")
# give a name to your class
class(movieList) <- "movie"
movieList
Output:
$name
[1] "Iron man"
$leadActor
[1] "Robert Downey Jr"
In S3 systems, methods don't belong to the class. They belong to generic functions. It means that
we can't create our own methods here, as we do in other programming languages like C++ or Java.
But we can define what a generic method (for example print) does when applied to our objects.
Statistical Computing & R Programming Page 6
Example:
print(movieList)
Output:
$name
[1] "Iron man"
$leadActor
[1] "Robert Downey Jr"
S4 Class
S4 class is an improvement over the S3 class. They have a formally defined structure which helps
in making objects of the same class look more or less similar .
In R, we use the setClass() function to define a class. For example
setClass("Student_Info", slots=list(name="character", age="numeric", GPA="numeric"))
Here, we have created a class named Student_Info with three slots (member
variables): name, age, and GPA.
Now to create an object, we use the new() function. For example,
student1 <- new("Student_Info", name = "John", age = 21, GPA = 3.5)
Here, inside new() , we have provided the name of the class "Student_Info" and value for all
three slots.
We have successfully created the object named student1
Examples:
# create a class "Student_Info" with three member variables
setClass("Student_Info", slots=list(name="character", age="numeric", GPA="numeric"))
# create an object of class
student1 <- new("Student_Info", name = "John", age = 21, GPA = 3.5)
# call student1 object
student1
Statistical Computing & R Programming Page 7
Output:
An object of class "Student_Info"
Slot "name":
[1] "John"
Slot "age":
[1] 21
Slot "GPA":
[1] 3.5
Here, we have created an S4 class named Student_Info using the setClass() function and an object
named student1 using the new() function.
Reference Class:
Reference classes were introduced later, compared to the other two. It is more similar to the object-
oriented programming we are used to seeing in other major programming languages.
Defining a reference class is similar to defining a S4 class. Instead of setClass() we use the
setRefClass() function. For example,
Example:
# create a class "Student_Info" with three member variables
Student_Info <- setRefClass("Student_Info",
fields = list(name = "character", age = "numeric", GPA = "numeric"))
# Student_Info() is our generator function which can be used to create new objects
student1 <- Student_Info(name = "John", age = 21, GPA = 3.5)
# call student1 object
student1
Example:
Reference class object of class "Student_Info"
Field "name":
[1] "John"
Field "age":
[1] 21
Field "GPA":
[1] 3.5
Statistical Computing & R Programming Page 8
Coersion:
Coersion includes type conversion. Type conversion means change of one type of data into another
type of data. We have two types of coercion.
1. Implicit coercion
2. Explicit coercion
Explicit Coercion :
In explicit coercion, we can change one data type to another data type by applying function.
We create an object "x" which stores integer values from 1 to 6.
x<-0:6
We can check data type of "x" object.
class(x)
We used [Link]() to change integer data type to numeric data type.
z<-[Link](x)
We check data type of z. It shows "numeric" data type.
class(z)
x<-0:6
class (x)
[1] "integer"
z<- [Link](x)
class (z)
[1] "numeric"
We can also change character data to numeric data as:
v<-c("1","2")
v
[1] "1" "2"
[Link](v)
[1] 1 2
We also changed logical data to character data.
x<-c(T,F)
x
[1]
Statistical Computing & R Programming Page 9
TRUE FALSE
y<-[Link] (x)
y
[1] "TRUE" "FALSE"
We also changed integer data to Logical data as:
X<-0:6
X
[1] 0 1 2 3 4 5 6
f<-[Link](x)
f
[1] FALSE TRUE TRUE TRUE TRUE TRUE TRUE
When we changed numeric or integer to logical data, it will store 0 as FALSE and other
values as TRUE. You can see here also .
x<-c(-1,2,0)
x
[1] -1 2 0
class (x)
[1] "numeric"
f<-as. logical(x)
f
[1] TRUE TRUE FALSE
Some exceptions of explicit coercion :-
x<-c("a","b","c")
v<- [Link](x)
warning message:
NAs introduced by coercion
v
[1] NA NA NA
We are converting character data type to numeric data type. It will show NA. It will show
missing in out object. It will not change character data to numeric because it includes values
“a” which cannot be changed to numeric data.
Statistical Computing & R Programming Page 10
Implicit Coercion :
When type conversion occurs by itself in R.
We input numeric and character data in an object. R converts numeric data to character data
by itself.
x<-c(1.7, "a")
x
[1] "1.7" "a"
We input logical and numeric data in an object. Logical data convert to numeric data
implicitly.
> y<-c(TRUE,5)
>y
[1] 1 5
There are many types of objects to store R-object. The frequently used objects are
Vectors
Matrices
Arrays
Factors
Data Frames
Lists
Table
Statistical Computing & R Programming Page 11
Basic plots in R
R has a number of built-in tools for basic graph types such as histograms, scatter plots, bar charts,
boxplots and much more. Rather than going through all of different types, we will focus on plot(),
a generic function for plotting x-y data.
To get a quick view of the different things you can do with plot, let's use the example() function:
example("plot")
Scatterplot
For some hands-on practice we are going to use plot to draw a scatter plot and obtain a graphical
view of the relationship between two sets of continuous numeric data. From our new_metadata
file we will take the samplemeans column and plot it against age_in_days, to see how mean
expression changes with age.
Now our metadata has all the information to draw a scatterplot. The base R function to do this is
plot(y ~ x, data):
Example:
x <- c(5,7,8,7,2,2,9,4,11,12,9,6)
y <- c(99,86,87,88,111,103,87,94,78,77,85,86)
plot(x, y, main="Observation of Cars", xlab="Car age", ylab="Car speed",pch=19)
Statistical Computing & R Programming Page 12
Here’s what the code does in more detail:
1. plot(x, y, main="Observation of Cars", xlab="Car age", ylab="Car speed",pch=19)
o main="Scatterplot example" sets the title of the plot to “Scatterplot example”.
o xlab="car age" sets the label for the x-axis to “car age”.
o ylab="car speed" sets the label for the y-axis to “car speed”.
o pch=19 sets the plotting character to a solid circle
Barplot:
Barplots are useful for comparing the distribution of a quantitative variable (numeric) between
groups or categories. A barplot would be much more useful to compare the samplemeans (numeric
variable) for each sample. We can use barplot to draw a single bar representing each sample and
the height indicates the average expression level.
Similar to the scatterplot, we can use additional arguments to specify the aesthetics that we want
to change. For example, changing axis labeling and adding some color.
Example:
x <- c("A", "B", "C", "D")
y <- c(2, 4, 6, 8)
barplot(y, [Link] = x, col = "red")
[Link] is an argument in the barplot() function in R that specifies the names of the bars in a bar
plot 1. It is a character vector that can be used to label the bars in a bar plot with custom names.
Statistical Computing & R Programming Page 13
For example, if you have a bar plot that shows the concentration of different carbon compounds,
you can use [Link] to label each bar with the name of the compound.
Histogram:
If we are interested in an overall distribution of numerical data, a histogram is what we'd want.
To plot a histogram of the data use the hist command:
hist(new_metadata$samplemeans)
Again, there are many options that we can change by modifying the default parameters. Let's color
in the bars, remove the borders and increase the number of breaks:
# Create data for the graph.
v <- c(19, 23, 11, 5, 16, 21, 32, 14, 19, 27, 39)
# Create the histogram.
hist(v, xlab = "[Link] Articles", col = "darkgray",border = "black", xlim = c(0, 50),
ylim = c(0, 5), breaks = 5)
Statistical Computing & R Programming Page 14