Lec 4 Basics of R
Lec 4 Basics of R
R Variables Concatenate
name <- "John"
Elements
You can also concatenate, or join, two or
age <- 40 more elements, by using
the paste() function.
In R, we can use both = and <- as assignment operators. text <- "awesome"
paste(text1, text2)
Multiple
Variables
# Assign the same value to multiple variables in one line
var1 <- var2 <- var3 <- "Orange"
Variable Names
• A variable name must start with a letter and can be a combination of letters, digits,
period(.) and underscore(_)
• If it starts with period(.), it cannot be followed by a digit
• A variable name cannot start with a number or underscore (_)
• Variable names are case-sensitive (age, Age and AGE are three different variables)
• Reserved words cannot be used as variables (TRUE, FALSE, NULL, if...)
We can use the class() function to check the data type of a variable
# numeric
x <- 10.5
class(x)
Type Conversion
You can convert from one type to another with the following functions:
• as.numeric()
x <- 1L # integer
• as.integer()
y <- 2 # numeric
• as.complex()
# convert from integer to numeric:
a <- as.numeric(x)
str
cat(str)
nchar(str)
Escape characters
Operators
Conditional statements
a <- 200
b <- 33
c <- 500
fruits
i <- 1
<- list("a", "b", "c")
while (i < 6) {
i <- i + 1
for (x in fruits) {
if(i==3)
print(x)
{
}
next # skip an iteration
} dice <- c(1, 2, 3, 4, 5, 6)
print(i)
if (i == 4) { for (x in dice) {
break # stop the loop print(x)
} }
}
adj <- list("red", "big", "tasty")
fruits <- list("apple", "banana", "cherry")
for (x in adj) {
for (y in fruits) { print(paste(x,
y)) }
}
Functions
A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function.
# List of strings
thislist <- list("apple", "banana", "cherry")
thislist[1]
thislist[1]
<- "blackcurrant"
# To add an item to the end of the list
append(thislist, "orange")
Compared to matrices, arrays can have more than two dimensions. Arrays can only
have one data type
# An array with one dimension with values ranging from 1 How does dim=c(4,3,2) work?
multiarray[2, 3, 2] #22
multiarray[c(1),,1]
multiarray[,c(1),1]
Data Frame
• Data Frames are data displayed in a format as a table.
• Data Frames can have different types of data inside it.
• Column name should be non empty. Row name should be unique
• However, each column should have the same type of data.
summary(Data_Frame)
Data Frame
Use the rbind() function to add new rows in a Data Frame
You can also set the levels, by adding the levels argument inside the factor() function
Factors
To access the items in a factor, refer to the index number, using [] brackets
R script
test.R
myobject
plot(myobject)
Click on Run