This article will help you understand the basics of R, which is required to start your data analysis learning.
Variables in R
Variables are used to stored information. In R programming, the"<-"
operator is used to assign variables.
class()
function is used to know the datatypes of a variable.
Few examples can be
skill<- "Programming"
age <- 12
# know the data type of variable
class(age)
Data types in R
Like any other programming language, R also has data types. They are
- numeric - Real numbers (e.g. 2, 10.55, 1000)
- integer - integers (2,5,100)
- character - string, characters (e.g "A", "Programming", "12.2")
- logic - boolean values (
TRUE, FALSE
) - complex - complex numbers
There are five additional data types defined in R
The function c()
is used to create a vector in R
# example of vectors
countries <- c("US", "Canada", "Brazil", "France")
age <- c(12, 56, 30, 20, 33, 12)
Operators in R
Like any programming language, R also has many operators. Here is the list.
age <- c(12, 56, 30, 33, 70, 12, 80, 90)
# check age more than 30
print( age > 30)
[1] FALSE TRUE FALSE TRUE TRUE FALSE TRUE TRUE
# check age less than 70
print( age > 30)
[1] TRUE TRUE TRUE TRUE FALSE TRUE FALSE FALSE
# check age is more than 30 and less than 70
print( age > 30 & age < 70)
[1] FALSE TRUE FALSE TRUE FALSE FALSE FALSE FALSE
Conditions in R
There are many conditional statements in R. Few of them are
- if statement
- if..else
- if..else..if
- ifelse()
if statement
a <- 30
b <- 20
if (a > b) {
print("A is greater than B")
}
[1] "A is greater than B"
if..else statement
a <- 10
b <- 20
if (a > b) {
print("A is greater than B")
} else {
print("B is greater than A")
}
[1] "B is greater than A"
if..else..if statement
a <- 10
b <- 10
if (a > b) {
print("A is greater than B")
} else if (b > a) {
print("B is greater than A")
} else {
print(" A and B are equal")
}
[1] " A and B are equal"
ifelse() statement
ifelse() is a powerful function used for vector bases operations
x <- c(2,3,4,5,6,7)
odd_even = ifelse(x%%2 == 0, "even", "odd")
> print(x)
[1] 2 3 4 5 6 7
> print(odd_even)
[1] "even" "odd" "even" "odd" "even" "odd"
Function in R
Functions are a powerful part of any programming language. The syntax to write a function in R is
functionName <- function(<arguments>){
# Statement
return(<returnvalue>)
}
Example: Function to check if a number is even or odd can be
check_odd_even = function(x){
if (x %% 2 == 0){
return("EVEN")
} else {
return ("ODD")
}
}
> check_odd_even(4)
[1] "EVEN"
>
Summary of learning
- Variables in R
- Data types in R
- Operators in R
- Conditions in R
- Function in R