# Assigning values to variables
<- 10
x <- 5
y # Printing variables
print(x)
[1] 10
print(y)
[1] 5
# Commenting
# This is a single line comment
R has a syntax that allows users to perform calculations and create variables to store data. Here is how you can assign values to variables and print them:
R supports various data types, including numeric, character, logical, and more. Here’s how you can create different types of variables:
[1] "x is greater than 15"
# If-else statement example
y <- 10
if (y > 15) {
print("y is greater than 15")
} else {
print("y is not greater than 15")
}
[1] "y is not greater than 15"
# If- else if-else statement example
z <- 10
if (z > 15) {
print("z is greater than 15")
} else if (z < 5) {
print("z is less than 5")
} else {
print("z is between 5 and 15")
}
[1] "z is between 5 and 15"
# Nested if example
a <- 20
if (a > 10) {
if (a < 30) {
print("a is greater than 10 and less than 30")
}
}
[1] "a is greater than 10 and less than 30"
# For loop example
for (i in 1:5) {
print(paste("Value of i is:", i))
}
# While loop example
count <- 1
while (count <= 5) {
print(paste("Count is:", count))
count <- count + 1 # Increment the count
}
# Repeat loop example
num <- 1
repeat {
print(paste("Number is:", num))
num <- num + 1
if (num > 5) {
break # Exit the loop
}
#Break Statement
}
for (i in 1:10) {
if (i == 6) {
break # Exit the loop if i equals 6
}
print(i)
}
#Next Statement
for (i in 1:10) {
if (i %% 2 == 0) { # Skip even numbers
next
}
print(i)
}
In R, collections refer to data types that can hold multiple values. The most common collections in R are vectors, lists, matrices, data frames, and factors.
Vectors are the simplest type of collection in R and can contain elements of the same type (numeric, character, logical, etc.). They are one-dimensional arrays that can be created using the c() function.
Lists can contain elements of different types, such as numbers, strings, vectors, and even other lists. They are created using the list() function.
Matrices are two-dimensional arrays that contain elements of the same type. They are created using the matrix() function, specifying the number of rows and columns.
Data frames are similar to matrices but can contain different types of elements in each column, much like a spreadsheet. They are created using the data.frame() function.
Factors are used to handle categorical data and store both the raw data and the levels of the categories. They are created using the factor() function.