0% found this document useful (0 votes)
7 views47 pages

R Program

The document contains a series of R programming examples covering various topics such as temperature conversion, area calculation for different shapes, finding even numbers, and performing basic string manipulations. It also includes examples of working with lists, data frames, vectors, and implementing a simple calculator and prime number finder. Each section provides code snippets along with sample outputs demonstrating the functionality of the programs.

Uploaded by

23uca001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views47 pages

R Program

The document contains a series of R programming examples covering various topics such as temperature conversion, area calculation for different shapes, finding even numbers, and performing basic string manipulations. It also includes examples of working with lists, data frames, vectors, and implementing a simple calculator and prime number finder. Each section provides code snippets along with sample outputs demonstrating the functionality of the programs.

Uploaded by

23uca001
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1.

TEMPERATURE CONVERSION
PROGRAM :
fahrenheit_to_celsius <- function(fahrenheit) {
celsius <- (fahrenheit - 32) * 5/9
return(celsius)
}

celsius_to_fahrenheit <- function(celsius) {


fahrenheit <- (celsius * 9/5) + 32
return(fahrenheit)
}
repeat {
cat("Temperature Conversion Program\n")

cat("1. Convert Fahrenheit to Celsius\n")


cat("2. Convert Celsius to Fahrenheit\n")
cat("3. Exit\n")
choice <- [Link](readline(prompt = "Enter your choice (1, 2, or 3): "))
if (choice == 1) {
temp_fahrenheit <- [Link](readline(prompt = "Enter temperature in Fahrenheit: "))
temp_celsius <- fahrenheit_to_celsius(temp_fahrenheit)

cat(temp_fahrenheit, "degrees Fahrenheit is equal to", temp_celsius, "degrees Celsius.\n\n")


} else if (choice == 2) {
temp_celsius <- [Link](readline(prompt = "Enter temperature in Celsius: "))
temp_fahrenheit <- celsius_to_fahrenheit(temp_celsius)
cat(temp_celsius, "degrees Celsius is equal to", temp_fahrenheit, "degrees Fahrenheit.\n\n")
} else if (choice == 3) {

cat("Exiting program. Goodbye!\n")


break
} else {
cat("Invalid choice. Please enter 1, 2, or 3.\n\n")
}
}

OUTPUT:
> source("F:\\r program\\fahrenheit.r")
Temperature conversion program
[Link] fahrenheit to celsius
[Link] celsius to fahrenheit

[Link]
Enter your choice(1,2 or 3):1
Enter temperature in fahrenheit:22
22 degrees fahrenheit is eqaul to -5.555556 degrees celsius.
Temperature conversion program
[Link] fahrenheit to celsius

[Link] celsius to fahrenheit


[Link]
Enter your choice(1,2 or 3):2
Enter temperature in celsius:-5.555556
-5.555556 degrees celsius is eqaul to 22 degrees fahrenheit.
2. CALCUTE THE AREA OF RECTANGLE, SQUARE, CIRCLE AND
TRIANGLE
PROGRAM :
calculate_rectangle_area<-function(){
length<-[Link](readline(prompt="Enter the length of the rectangle:"))
width<-[Link](readline(prompt="Enter the width of the rectangle:"))
area<-length*width

cat("Area of the rectangle",area,"\n")


}
calculate_square_area<-function(){
side<-[Link](readline(prompt="enter the side length of the square:"))
area<-side*side
cat("Area of the square",area,"\n")

}
calculate_circle_area<-function(){
radius<-[Link](readline(prompt="Enter the radius of the circle:"))
area<-pi*radius^2
cat("Area of the circle:",area,"\n")
}
calculate_triangle_area<-function(){
base<-[Link](readline(prompt="Enter the base of the triangle:"))
height<-[Link](readline(prompt="enter the height of the triangle:"))
area<-0.5*base*height
cat("Area of the triangle:",area,"\n")
}

while(TRUE){
cat("\nselect a shape to calculate its area:\n")
cat("[Link]\n")
cat("[Link]\n")
cat("[Link]\n")
cat("[Link]\n")

cat("[Link]\n")
choice<-[Link](readline(prompt="Enter your choice(1-5):"))
if(choice==1){
calculate_rectangle_area()
}
else if(choice==2){

calculate_square_area()
}
else if(choice==3){
calculate_circle_area()
}
else if (choice== 4){

calculate_triangle_area()
}
else if(choice==5){
cat("exiting program.\n")
break
}

else{
cat("Invalid choice please enter a number between 1 and 5.\n")
}
}
OUTPUT :
> source("F:\\r program\\calculate.r")
select a shape to calculate its area:
[Link]

[Link]
[Link]
[Link]
[Link]
Enter your choice(1-5):1
Enter the length of the rectangle:3

Enter the width of the rectangle:2


Area of the rectangle 6
3. LIST OF EVEN NUMBERS
PROGRAM :
find_even_numbers<-function(n){
even_numbers<-c()
for(i in 1:n){
if(i%%2==0){

even_numbers<-c(even_numbers,i)
}
}
return(even_numbers)
}
n_value<-20

result<-find_even_numbers(n_value)
print(paste("Even numbers from 1 to ",n_value,"are:"))
print(result)

OUTPUT :
> source("F:\\r program\\even.r")
[1] "Even numbers from 1 to 20 are:"

[1] 2 4 6 8 10 12 14 16 18 20
4. SQUARE OF NUMBERS IN SEQUENCE
PROGRAM :
Print_Squares_in_Sequence<-function(n)
{
numbers<-1:n
squares<-numbers^2

for(i in 1:length(numbers))
{
cat(numbers[i],"^2=",squares[i],"\n")
}
}
Print_Squares_in_Sequence(5)

OUTPUT :
> source("F:\\r program\\square.r")
1 ^2= 1
2 ^2= 4
3 ^2= 9
4^2= 16

5^2= 25
5. CBIND() AND RBIND()
PROGRAM :
cat("\t CBIND()","\n")
df1<-[Link](

Name=c("Alice","Bob"),
Age=c(25,30)
)
df2<-[Link](
Height=c(160,175),
Weight=c(55,70)

)
combined_df_cols<-cbind(df1,df2)
print(combined_df_cols)

cat("\t RBIND()","\n")
df3<-[Link](

Name=c("Charlie","David"),
Score=c(90,85)
)
df4<-[Link](
Name=c("Eve","Frank"),
Score=c(92,88)

)
combined_df_rows<-rbind(df3,df4)
print(combined_df_rows)
OUTPUT :
> source("F:\\r program\\cbind.r")

CBIND()
Name Age Height Weight

1 Alice 25 160 55
2 Bob 30 175 70

RBIND()
Name Score
1 Charlie 90
2 David 85

3 Eve 92
4 Frank 88
6. STRING MANIPULATION
PROGRAM :
my_string<-"R programming is FUN!"
cat("Number of characters:",nchar(my_string),"\n")
cat("UpperCase:",toupper(my_string),"\n")
cat("LowerCase:",tolower(my_string),"\n")

cat("substring(char 3 to 10):",substr(my_string,3,10),"\n")
string1<-"Hello"
string2<-"World"
cat("Concatenated string:",paste(string1,string2),"\n")
cat("Concatenated with separator:",paste(string1,string2,sep="-"),"\n")
split_string<-strsplit(my_string," ")

cat("Split string:",unlist(split_string),"\n")
modified_string_sub<-sub("programming","Coding",my_string)
cat("After sub():",modified_string_sub,"\n")
another_string<-"Apple Pie,apple juice,apple sauce"
modified_string_gsub<-gsub("Apple","Orange",another_string)
cat("After gsub():",modified_string_gsub,"\n")
matching_indices<-grep("is",my_string)

cat("Indices where 'is' is found:",matching_indices,"\n")


contains_fun<-grepl("FUN",my_string)
cat("Does the string contain 'FUN'?",contains_fun,"\n")

OUTPUT :
> source("F:\\r program\\string.r")

Number of characters: 21
UpperCase: R PROGRAMMING IS FUN!
LowerCase: r programming is fun!
substring(char 3 to 10): programm
Concatenated string: Hello World
Concatenated with separator: Hello-World

Split string: R programming is FUN!


After sub(): R Coding is FUN!
After gsub(): Orange Pie,apple juice,apple sauce
Indices where 'is' is found: 1
Does the string contain 'FUN'? TRUE
7. LIST
PROGRAM :
my_list<-list(name="John doe",age=25,scores=c(90,85,92),details=list(city="New
York",zip=10001))
print(my_list)
cat("\t PRINTING LIST WITH COMMAND \n")
print(my_list$name)
print(my_list[["name"]])
cat("\t PRINTING LIST WITH INDEX \n")

print(my_list[[2]])
print(my_list[[3]][1])
cat("\t SUBSET THE LIST \n")
subset_list<-my_list[c("name","age")]
print(subset_list)
cat("\t MODIFY THE LIST \n")

my_list$age<-26
my_list[[3]]<-c(95,88,91)
print(my_list)
cat("\t ADDING THE LIST \n")
my_list$email<-"john@[Link]"
print(my_list)

cat("\t DELETING THE LIST \n")


my_list$email<-NULL
print(my_list)
cat("\t MERGING THE LIST \n")
list1<-list(1,2)
list2<-list("a","b")
merged_list<-c(list1,list2)
print(merged_list)
cat("\t CONVERT TO THE VECTOR\n")
score_list<-list(90,85,92)

score_vector<-unlist(score_list)
print(score_vector)

OUTPUT :
> source("F:\\r program\\list.r")
$name

[1] "John doe"


$age
[1] 25
$scores
[1] 90 85 92
$details

$details$city
[1] "New York"
$details$zip
[1] 10001
PRINTING LIST WITH COMMAND
[1] "John doe"

[1] "John doe"


PRINTING LIST WITH INDEX
[1] 25
[1] 90
SUBSET THE LIST
$name
[1] "John doe"
$age
[1] 25

MODIFY THE LIST


$name
[1] "John doe"
$age
[1] 26

$scores
[1] 95 88 91
$details
$details$city
[1] "New York"
$details$zip

[1] 10001
ADDING THE LIST
$name
[1] "John doe"
$age
[1] 26

$scores
[1] 95 88 91
$details
$details$city
[1] "New York"
$details$zip
[1] 10001
$email
[1] "john@[Link]"

DELETING THE LIST


$name
[1] "John doe"
$age
[1] 26
$scores

[1] 95 88 91
$details
$details$city
[1] "New York"
$details$zip
[1] 10001

MERGING THE LIST


[[1]]
[1] 1
[[2]]
[1] 2
[[3]]

[1] "a"
[[4]]
[1] "b"
CONVERT TO THE VECTOR
[1] 90 85 92
8. SIMPLE CALCULATOR
PROGRAM :
num1<-[Link](readline(prompt="Enter First Number:"))
num2<-[Link](readline(prompt="Enter Second Number:"))
while(TRUE){

cat("Select Operation:\n")
cat("[Link]\n")
cat("[Link]\n")
cat("[Link]\n")
cat("[Link]\n")
cat("[Link]\n")

selected_option<-[Link](readline(prompt="Enter choice(1/2/3/4/5):"))
switch(selected_option,
'1'={result<-num1+num2},
'2'={result<-num1-num2},
'3'={result<-num1*num2},
'4'={
if(num2!=0){

result<-num1/num2
}else{
result<-"Undefined (division by zero)"
}
},
'5'={result<-num1%%num2},{result<-"Invalid choice"}

)
cat("Result:",result,"\n")
}

OUTPUT :
> source("F:\\r program\\simplecalculator.r")
Enter First Number:2

Enter Second Number:3

Select Operation:
[Link]
[Link]
[Link]
[Link]

[Link]
Enter choice(1/2/3/4/5):1
Result: 5

Select Operation:
[Link]
[Link]

[Link]
[Link]
[Link]
Enter choice(1/2/3/4/5):2
Result: -1
9. PRIME NUMBER
PROGRAM :
N<-[Link](readline(prompt="Enter the value of N:"))
is_prime<-function(num){

if(num<=1){
return(FALSE)
}
for(i in 2:sqrt(num)){
if(num%%i==0){
return(FALSE)

}
}
return(TRUE)
}
cat("Prime numbers upto",N,"are: \n")
for(i in 2:N){

if(is_prime(i)){
cat(i," ")
}
}

OUTPUT :
> source("F:\\r program\\prime.r")
Enter the value of N:7
Prime numbers upto 7 are: 3 5 7
10. VECTOR

PROGRAM :
ages<-c(22,25,45,30,19)
print(ages)
cat("\t TYPE AND LENGTH \n")
print(typeof(ages))
print(length(ages))

cat("\t SUM AND MEAN THE AGES \n")


sum_ages<-sum(ages)
mean_ages<-mean(ages)
cat("Sum:",sum_ages,"\n")
cat("Mean:",mean_ages,"\n")
cat("\t MIN AND MAX THE AGES \n")

min_age<-min(ages)
max_age<-max(ages)
cat("Min Age:",min_age,"\n")
cat("Max Age:",max_age,"\n")
cat("\t PRINTING THE FIRST AGE \n")
first_age<-ages[1]

print(first_age)
cat("\t RANGE OF ELEMETS(2nd to 4th)\n")
selected_ages<-ages[2:4]
print(selected_ages)
cat("\t NON-CONSECUTIVE ELEMENTS \n")
specific_ages<-ages[c(1,3,5)]
print(specific_ages)
age_gt_25<-ages[ages>25]
print(age_gt_25)
cat("\t SORT AGES IN ASCENDING ORDER \n")
sorted_ages_asc<-sort(ages)

print(sorted_ages_asc)
cat("\t SORT AGES IN DESCENDING ORDER \n")
sorted_ages_desc<-sort(ages,decreasing=TRUE)
print(sorted_ages_desc)

OUTPUT :
> source("F:\\r program\\vectors.r")
[1] 22 25 45 30 19
TYPE AND LENGTH
[1] "double"
[1] 5
SUM AND MEAN THE AGES

Sum: 141
Mean: 28.2
MIN AND MAX THE AGES
Min Age: 19
Max Age: 45
PRINTING THE FIRST AGE

[1] 22
RANGE OF ELEMETS(2nd to 4th)
[1] 25 45 30
NON-CONSECUTIVE ELEMENTS
[1] 22 45 19
[1] 45 30
SORT AGES IN ASCENDING ORDER
[1] 19 22 25 30 45
SORT AGES IN DESCENDING ORDER

[1] 45 30 25 22 19
11. DATA FRAMES
PROGRAM :
Name<-c("Alice","Bob","Charlie","David","Emma")
Age<-c(24,27,22,23,25)
Grade<-c(85.5,72.0,91.5,88.0,79.5)
cat("\t CREATE THE DATA FRAME \n")

students_df<-[Link](Name,Age,Grade)
print(students_df)
cat("\t INSPECT THE DATA FRAME \n")
print(str(students_df))
print(summary(students_df))
print(head(students_df))

print(dim(students_df))
cat("\t ACCESS A SPECIFIC COLUMN USING THE $ OPERATOR \n")
print(students_df$Name)
cat("\t MODIFY THE VALUE IN THE DATAFRAME \n")
students_df[2,3]<-75.0
print(students_df)
cat("\t ADD NEW COLUMN \n")

students_df$pass<-students_df$Grade>=80
print(students_df)
cat("\t REMOVE A COLUMN \n")
students_df$Age<-NULL
print(students_df)
cat("\t EXTRACTING ONLY STUDENTS WHO PASSED \n")

passing_students<-students_df[students_df$pass==TRUE,]
print(passing_students)
cat("\t SELECT ONLY SPECIFIC COLUMNS \n")
name_grade_df<-students_df[,c("Name","Grade")]
print(name_grade_df)
cat("\t FILTER USING A CONDITION \n")

high_achievers<-subset(students_df,Grade>90)
print(high_achievers)

OUTPUT :
> source("F:\\r program\\dataframes.r")
CREATE THE DATA FRAME

Name Age Grade


1 Alice 24 85.5
2 Bob 27 72.0
3 Charlie 22 91.5
4 David 23 88.0
5 Emma 25 79.5

INSPECT THE DATA FRAME


'[Link]': 5 obs. of 3 variables:
$ Name : chr "Alice" "Bob" "Charlie" "David" ...
$ Age : num 24 27 22 23 25
$ Grade: num 85.5 72 91.5 88 79.5
NULL

Name Age Grade


Length:5 Min. :22.0 Min. :72.0
Class :character 1st Qu.:23.0 1st Qu.:79.5
Mode :character Median :24.0 Median :85.5
Mean :24.2 Mean :83.3
3rd Qu.:25.0 3rd Qu.:88.0
Max. :27.0 Max. :91.5
Name Age Grade
1 Alice 24 85.5

2 Bob 27 72.0
3 Charlie 22 91.5
4 David 23 88.0
5 Emma 25 79.5
[1] 5 3
ACCESS A SPECIFIC COLUMN USING THE $ OPERATOR

[1] "Alice" "Bob" "Charlie" "David" "Emma"


MODIFY THE VALUE IN THE DATAFRAME
Name Age Grade
1 Alice 24 85.5
2 Bob 27 75.0
3 Charlie 22 91.5

4 David 23 88.0
5 Emma 25 79.5
ADD NEW COLUMN
Name Age Grade pass
1 Alice 24 85.5 TRUE
2 Bob 27 75.0 FALSE

3 Charlie 22 91.5 TRUE


4 David 23 88.0 TRUE
5 Emma 25 79.5 FALSE
REMOVE A COLUMN
Name Grade pass
1 Alice 85.5 TRUE
2 Bob 75.0 FALSE
3 Charlie 91.5 TRUE
4 David 88.0 TRUE

5 Emma 79.5 FALSE


EXTRACTING ONLY STUDENTS WHO PASSED
Name Grade pass
1 Alice 85.5 TRUE
3 Charlie 91.5 TRUE
4 David 88.0 TRUE

SELECT ONLY SPECIFIC COLUMNS


Name Grade
1 Alice 85.5
2 Bob 75.0
3 Charlie 91.5
4 David 88.0

5 Emma 79.5
FILTER USING A CONDITION
Name Grade pass
3 Charlie 91.5 TRUE
12. BAR CHART
PROGRAM :
article_counts<-c(17,32,8,53,1)
months<-c("Jan","Feb","Mar","Apr","May")
barplot(article_counts,
[Link]=months,

xlab="Month",
ylab="Number of Articles",
main="Article publication per month",
col="skyblue")

OUTPUT :
13. PIE CHART
PROGRAM :
expenditure<-c(600,300,150,100,200)
categories<-c("Housing","Food","Transport","Leisure","Utilities")
piepercent<-round(100*expenditure/sum(expenditure),1)
pie(expenditure,

labels=piepercent,
main="Monthly Expenditure Breakdown",
col=rainbow(length(expenditure)))
legend("topright",categories,cex=0.8,fill=rainbow(length(expenditure)))

OUTPUT :
14. ODD OR EVEN
PROGRAM :
count_even_odd<-function(){
N_str<-readline(prompt="Enter the number of elements (N):")
N<-[Link](N_str)
if([Link](N)||N<=0){

cat("Invalid input for the number of elements. Please enter a positive integer.\n")
return()
}
numbers<-vector("numeric",N)
cat(sprintf("Enter %d numbers,one by one:\n",N))
for(i in 1:N){

input_str<-readline(prompt=sprintf("Number%d:",i))
num<-[Link](input_str)
if([Link](num)){
cat("Invalid number entered. Exiting program.\n")
return()
}
numbers[i]<-num

}
even_count<-0
odd_count<-0
for(num in numbers){
if(num%%2==0){
even_count<-even_count+1

}
else
{
odd_count<-odd_count+1
}
}

cat(sprintf("\n From the input array(%s):\n",paste([Link]=",")))


cat(sprintf("Number of even numbers: %d\n",even_count))
cat(sprintf("Number of odd numbers: %d\n",odd_count))
}
count_even_odd()

OUTPUT :
> source("F:\\r program\\oddeven.r")
Enter the number of elements (N):3
Enter 3 numbers,one by one:
Number1:1
Number2:2

Number3:3
From the input array(,):
Number of even numbers: 1
Number of odd numbers: 2
15. FACTORIAL
PROGRAM :
factorial_recursive<-function(n){
if(n<=1){
return(1)
}else{

return(n*factorial_recursive(n-1))
}
}
cat("Enter a non-negative integer:")
num<-[Link](readline())
if([Link](num)||num<0){

cat("Invalid [Link] enter a non-negative integer.\n")


}else{
result<-factorial_recursive(num)
cat(sprintf("The factorial of %d is %d \n",num,result))
}

OUTPUT :
> source("F:\\r program\\fact.r")
Enter a non-negative integer:5
The factorial of 5 is 120
16. LEAP YEAR
PROGRAM :
year=[Link](readline(prompt="Enter a year:"))
if((year%%4)==0){
if((year%%100)==0){
if((year%%400)==0){

print(paste(year,"is a leap year"))


}else{
print(paste(year,"is not a leap year"))
}
}else{
print(paste(year,"is a leap year"))

}
}else{
print(paste(year,"is not a leap year"))
}

OUTPUT :
> source("F:\\r program\\leapyear.r")

Enter a year:2024
[1] "2024 is a leap year"
> source("F:\\r program\\leapyear.r")
Enter a year:2025
[1] "2025 is not a leap year"
17. GET INPUT FROM USER
PROGRAM :
[Link]<-readline(prompt="Enter a name:")
[Link]<-readline(prompt="Enter your roll no:")
[Link]<-readline(prompt="Enter your age:")
[Link]<-readline(prompt="Enter your email:")

[Link]<-readline(prompt="Enter your phone no:")


[Link]<-[Link]([Link])
[Link]<-[Link]([Link])
cat("HI",[Link],"\n")
cat("Roll no:",[Link],"\n")
cat("next year you will be",[Link]+1,"years old","\n")

cat("Email:",[Link],"\n")
cat("Phone number:",[Link],"\n")

OUTPUT :
> source("F:\\r program\\input.r")
Enter a name:Abi
Enter your roll no:23

Enter your age:19


Enter your email:abi@[Link]
Enter your phone no:9182736450
HI Abi
Roll no: 23
next year you will be 20 years old

Email: abi@[Link]

Phone number: 9182736450


18. READ A CSV FILE AND ANALYZE THE DATA IN THE FILE
CREATING CSV FILE :

PROGRAM :
read_data<-[Link]("F:/New Folder/[Link]",header=TRUE,stringsAsFactors=FALSE)
print(read_data)

cat("\n Total columns:",ncol(read_data))


cat("\n Total Rows:",nrow(read_data))
read_data$Month.<-gsub(",","",read_data$Month.)
read_data$X1958.<-[Link](gsub(",", "",read_data$X1958.))
read_data$X1959.<-[Link](gsub(",", "",read_data$X1959.))
read_data$X1960 <-[Link](gsub(",", "",read_data$X1960))

min_data<-min(read_data$X1960,[Link]=TRUE)
max_data<-max(read_data$X1958.,[Link]=TRUE)
cat("/n Min value(1960):",min_data)
cat("/n Max value(1958):",max_data)

OUTPUT :

> source("F:\\r program\\dataset1.r")

Month. X1958. X1959. X1960

1 JAN, 340, 360, 417

2 FEB, 380, 342, 391

3 MAR, 362, 406, 419


4 APR, 348, 397, 462

5 MAY, 363, 420, 472

6 JUN, 435, 472, 435

7 JUL, 491, 548, 622

8 AUG, 505, 559, 606

9 SEP, 404, 463, 508

10 OCT, 359, 407, 461

11 NOV, 310, 362, 390

Total columns: 4

Total Rows: 11

Min value(1960): 390

Max value(1958): 505


19. STATISTICAL ANALYSIS ON THE DATA
PROGRAM :

hours <- c(5,5,5, 10,10,10, 15,15,15, 20,20,20, 25,25,25)

marks <- c(45,50,55,

60,65,70,

70,75,80,

80,85,88,

90,95,98)

par(mfrow=c(2,2))

plot(hours, marks,

main = "Scatter Plot: Study Hours vs Exam Marks",

xlab = "Hours Studied",

ylab = "Exam Marks",

pch = 19, col = "blue")

abline(lm(marks ~ hours), col = "red", lwd=2)

barplot(marks,

main = "Bar Chart: Exam Marks of Students",

xlab = "Students",

ylab = "Marks",

col = rainbow(length(marks)),

[Link] = paste("S", 1:length(marks)),

las = 2,

[Link] = 0.8,

space = 0.5)

categories <- c("Below 60", "60-75", "Above 75")


counts <- c(sum(marks < 60), sum(marks >= 60 & marks <= 75), sum(marks > 75))

pie(counts,

labels = categories,

main = "Pie Chart: Exam Performance",

col = c("red", "yellow", "green"))

OUTPUT :
20. FACTOR
PROGRAM :

student_data <- [Link](


Name = c("Aman", "Riya", "Karan", "Sneha", "Rahul", "Priya"),
Course = c("BCA", "BBA", "BCA", "BCom", "BBA", "BCA"),
Grade = c("A", "B", "A", "C", "B", "A"),
Marks = c(85, 72, 90, 65, 75, 88)
)
student_data$Course <- factor(student_data$Course)
student_data$Grade <- factor(student_data$Grade,
levels = c("C", "B", "A"),
ordered = TRUE)
str(student_data)
cat("\nCourse Count:\n")

print(table(student_data$Course))
cat("\nGrade Summary:\n")
print(summary(student_data$Grade))
cat("\nAverage Marks by Course:\n")
print(aggregate(Marks ~ Course, data = student_data, mean))

OUTPUT :
'[Link]': 6 obs. of 4 variables:
$ Name : chr "Aman" "Riya" "Karan" "Sneha" ...
$ Course: Factor w/ 3 levels "BBA","BCA","BCom": 2 1 2 3 1 2
$ Grade : [Link] w/ 3 levels "C"<"B"<"A": 3 2 3 1 2 3
$ Marks : num 85 72 90 65 75 88
Course Count:
BBA BCA BCom
2 3 1
Grade Summary:

CBA
123
Average Marks by Course:
Course Marks
1 BBA 73.50000
2 BCA 87.66667

3 BCom 65.00000
21. MATH FUNCTION
PROGRAM :
num <- 25
num2 <- 5.7
cat("\n\t SQUARE ROOT ","\n")
sqrt_result <- sqrt(num)

cat("Square root of", num, "is:", sqrt_result, "\n")


cat("\n\t POWER FUNCTION ","\n")
power_result <- num^2
cat("Square of", num, "is:", power_result, "\n")
cat("\n\t ABSOLUTE VALUE","\n")
abs_result <- abs(-15)

cat("Absolute value of -15 is:", abs_result, "\n")


cat("\n\t CEILING FUNCTION ","\n")
ceil_result <- ceiling(num2)
cat("Ceiling value of", num2, "is:", ceil_result, "\n")
cat("\n\t FLOOR FUNCTION ","\n")
floor_result <- floor(num2)
cat("Floor value of", num2, "is:", floor_result, "\n")

cat("\n\t LOG FUNCTION ","\n")


result <- log10(1000)
cat("log10(1000) =", result)
cat("\n\t EXPONENTIAL FUNCTION ","\n")
exp_result <- exp(2)
cat("Exponential value of e^2 is:", exp_result, "\n")
OUTPUT :
SQUARE ROOT

Square root of 25 is: 5

POWER FUNCTION

Square of 25 is: 625

ABSOLUTE VALUE

Absolute value of -15 is: 15

CEILING FUNCTION

Ceiling value of 5.7 is: 6

FLOOR FUNCTION

Floor value of 5.7 is: 5

LOG FUNCTION

log10(1000) = 3

EXPONENTIAL FUNCTION

Exponential value of e^2 is: 7.389056


22. CLASS
PROGRAM :

library(methods)
setClass(
"Student",
slots=c(
name="character",
scores="numeric"
)
)
createStudent<-function(name,scores){
new("Student",name=name,scores=scores)
}
printStudent<-function(student){

cat("Student:",student@name,"\n")
cat("Scores:",paste(student@scores,collapse=","),"\n")
avg<-round(mean(student@scores),2)
cat("Average Score:",avg,"\n")
grade<-if(avg>=90)"A" else if(avg>=80)"B" else if(avg>=70)"C" else "D"
cat("Grade:",grade,"\n\n")

}
addScore<-function(student,score){
student@scores<-c(student@scores,score)
return(student)
}
s1<-createStudent("Alice",c(85,90,78))
s2<-createStudent("Bob",c(70,88,95))
printStudent(s1)
printStudent(s2)
s1<-addScore(s1,92)
s2<-addScore(s2,80)

printStudent(s1)
printStudent(s2)

OUTPUT :
Student: Alice
Scores: 85,90,78

Average Score: 84.33


Grade: B

Student: Bob
Scores: 70,88,95
Average Score: 84.33

Grade: B

Student: Alice
Scores: 85,90,78,92
Average Score: 86.25
Grade: B

Student: Bob
Scores: 70,88,95,80
Average Score: 83.25
Grade: B
23. FIND SUM,MEAN AND PRODUCT OF VECTOR,IGNORE NA
VALUES
PROGRAM :
x=c(10,NULL,20,30,NA)
print("Sum:")
print(sum(x,[Link]=TRUE))
print("Mean:")

print(mean(x,[Link]=TRUE))
print("Product:")
print(prod(x,[Link]=TRUE))

OUTPUT :
[1] "Sum:"

[1] 60
[1] "Mean:"
[1] 20
[1] "Product:"
[1] 6000
24. SEQUENCE OF NUMBERS TO FIND MEAN AND SUM
PROGRAM :
print("Sequence of numbers from 20 to 50:")
print(seq(20,50))
print("Mean of numbers from 20 to 60:")
print(mean(20:60))

print("Sum of numbers from 51 to 91:")


print(sum(51:91))

OUTPUT :
[1] "Sequence of numbers from 20 to 50:"
[1] 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
50
[1] "Mean of numbers from 20 to 60:"
[1] 40
[1] "Sum of numbers from 51 to 91:"

[1] 2911
25. MATRIX
PROGRAM :
A<-matrix(c(2,3,5,1,0,-2),nrow=2,byrow=TRUE)
B<-matrix(c(-2,0,4,3,2,1),ncol=2)
print(A)
print(B)

A_transpose<-t(A)
product_AB<-A%*%B
print(A_transpose)
print(product_AB)

OUTPUT :
[,1] [,2] [,3]
[1,] 2 3 5
[2,] 1 0 -2
[,1] [,2]
[1,] -2 3
[2,] 0 2
[3,] 4 1

[,1] [,2]
[1,] 2 1
[2,] 3 0
[3,] 5 -2
[,1] [,2]
[1,] 16 17

[2,] -10 1
26. CORRELATION AND COVARIANCE
PROGRAM :
x<-c(2,3,5,6,9)
y<-c(5,3,4,6,12)
correlation<-cor(x,y)
covariance<-cov(x,y)

print(paste("Correlation:",correlation))
print(paste("Covariance:",covariance))

OUTPUT :
[1] "Correlation: 0.852056336165632"
[1] "Covariance: 8.25"
27. NORMAL DISTRIBUTION
PROGRAM :
values<-rnorm(10,mean=50,sd=10)
values
mean_val<-mean(values)
print(paste("Calculated Mean:",mean_val))

sd_val<-sd(values)
print(paste("Calculated SD:",sd_val))
hist(values,main="Normal
Distribution(mean=50,SD=10)",xlab="values",col="lightblue",border="black")

OUTPUT :
[1] "Calculated Mean: 48.0897765795147"
[1] "Calculated SD: 9.27271508568294"

You might also like