Lab 2 - Lists, Vectors, Dataframes
Lab 2 - Lists, Vectors, Dataframes
frames in R
Lists in R
Lists are the R objects which contain elements of different types
like − numbers, strings, vectors and another list inside it. A list can
also contain a matrix or a function as its elements. List is created
using list() function
# List of strings
thislist <- list("apple", "banana", "cherry")
thislist
thislist <-
list("apple", "banana", "cherry", "orange",
"kiwi", "melon", "mango")
(thislist)[2:5]
R Vectors
A vector is simply a list of items that are of the
same type.
Alternative:
• Use vector of T and F values to select subset of elements
Data frames in R
• A data frame is a table or a two-dimensional array-
like structure in which each column contains values
of one variable and each row contains one set of
values from each column.
Following are the characteristics of a data frame.
• The column names should be non-empty.
• The row names should be unique.
• The data stored in a data frame can be of numeric,
factor or character type.
• Each column should contain same number of data
items
Data frame
# Create a data frame
Eg:
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
print(x)
}
Control Structures
Control statements
• if … else …
• for loops
• repeat loops
• while loops
Largest of two numbers
using simple if
a <- 33
b <- 200
if (b > a)
{
print("b is greater than a")
}
Largest of two numbers using
if … else
a <- 33
b <- 33
if (b > a)
{
print("b is greater than a")
} else
{
print ("a and b are equal")
}
For Loop
Syntax:
for (name in expr_1) expr_2
Example:
for (x in 1:10)
{
print(x)
}
while