1# Basic Data Types in R
# Create variables of different data types (numeric, character, logical, complex, raw).
#Check their data types.
#Create a factor variable and display its levels.
#Create a list containing different data types and display its structure.
#Convert a numeric value to character
num_var <- 10
char_var <- "Hello"
log_var <- TRUE
complex_var <- 3 + 4i
raw_var <-charToRaw("R")
typeof(num_var)
typeof(char_var)
typeof(log_var)
typeof(complex_var)
typeof(raw_var)
fruits <- factor(c("mango", "apple" , "banana" , "apple" ))
levels(fruits)
my_list <- list(num_var,char_var,log_var,complex_var,raw_var,fruits)
str(my_list)
as.character(num_var)
2#Built-in Functions in R
#Find the sum, maximum, minimum, mean, median, and standard deviation of a numeric vector.
#Sort a vector in ascending and descending order.
#Calculate square root, logarithm, and exponential values.
#Generate a sequence and repeat elements using built-in functions.
num_vec <- c(20,45,33,45,55,66,33)
sum(num_vec)
max(num_vec)
min(num_vec)
mean(num_vec)
median(num_vec)
sd(num_vec)
sort(num_var)
sort(num_var, decreasing=TRUE)
sqrt(225)
log(100)
exp(2)
seq(1, 20, by=2)
rep(c(1,2,3), times=3)
3#Operators in R
#Demonstrate arithmetic operators on vectors.
#Compare two vectors using relational operators.
#Demonstrate logical operators (&, |, !).
#Use %in% operator to test membership of elements in a vector
a <- c(100,200,300)
b <- c(400,500,600)
a+b
a-b
a*b
a/b
a>b
a==b
a<=b
x <- c(TRUE,FALSE,TRUE)
y<- c(TRUE, TRUE,FALSE)
x&y
x|y
!x
fruits <- c('apple', 'mango' , 'banana' ,'apple') 'apple' %in% fruits 'grape' %in% fruits
4#Creating and Manipulating Vectors
#Create two vectors and perform element-wise addition, subtraction, multiplication, and division.
#Access specific elements of a vector using indexing.
#Modify elements of a vector using conditional indexing.
v1 <- c(20,23,44,55,66)
v2 <- c(1,2,3,4,5)
v1+v2
v1-v2
v1*v2
v1/v2
v1[2]
v1[c(3,4,1)]
v2[2:5]
v1[v1> 44] <- 0
v1