0% found this document useful (0 votes)
39 views15 pages

R Lab

The document provides examples of R programs for various tasks like checking if a number is odd or even, finding if a number is prime, calculating factorial of a number, creating a simple calculator, finding Fibonacci sequence using recursion, inverting sex in a data frame, creating matrices from vectors using different functions, implementing data visualization using ggplot2, plotting bar chart and pie chart, and creating and accessing data frames like lists.
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)
39 views15 pages

R Lab

The document provides examples of R programs for various tasks like checking if a number is odd or even, finding if a number is prime, calculating factorial of a number, creating a simple calculator, finding Fibonacci sequence using recursion, inverting sex in a data frame, creating matrices from vectors using different functions, implementing data visualization using ggplot2, plotting bar chart and pie chart, and creating and accessing data frames like lists.
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
You are on page 1/ 15

INDEX

S.No Title Page.no Staff


Signature
Get the input from user and demonstrate working with operators
1.
(Arithmetic, Relational, Logical, Assignment operators).
2.
Check if a Number is Odd or Even

3 Check if the given Number is a Prime Number

4 Find the Factorial of a Number


Make a Simple Calculator
5

6 Find the Fibonacci sequence Using Recursive Function

7 Data frame, afterwards invert Sex for all individuals.

Create a Matrix from a Vector using dim() function, cbind()


8 function and
rbind().
9. Write an R Program to implement data visualization with ggplot2

10. Plot the bar chart and pie chart on sample data

11. Create and access a Data Frame like a List


1. Write a R-Program to get the input from user and demonstrate working with operators
(Arithmetic, Relational, Logical, Assignment operators).

Arithmetic OPerator
x <- 5
y <- 16
x+y
[1] 21
x-y
[1] -11
x*y
[1] 80
y/x
[1] 3.2
y%/%x
[1] 3
y%%x
[1] 1
y^x
[1] 1048576

Relational Operator

x <- 5
y <- 16
x<y
[1] TRUE
x>y
[1] FALSE
x<=5
[1] TRUE
y>=20
[1] FALSE
y == 16
[1] TRUE
x != 5
[1] FALSE

Logical OPerator

x <- c(TRUE,FALSE,0,6)
y <- c(FALSE,TRUE,FALSE,TRUE)
!x
[1] FALSE TRUE TRUE FALSE
x&y
[1] FALSE FALSE FALSE TRUE
> x&&y
[1] FALSE
x|y
[1] TRUE TRUE FALSE TRUE
x||y
[1] TRUE

Assignment Operator
> x <- 5
>x
[1] 5
>x=9
>x
[1] 9
> 10 -> x
>x
[1] 10
2. Write an R Program to Check if a Number is Odd or Even

# Program to check if the input number is odd or even.


# A number is even if division by 2 give a remainder of 0.
# If remainder is 1, it is odd.
num = as.integer(readline(prompt="Enter a number: "))
if((num %% 2) == 0) {
print(paste(num,"is Even"))
} else {
print(paste(num,"is Odd"))
}

Output 1

Enter a number: 89
[1] "89 is Odd"

Output 2

Enter a number: 0
[1] "0 is Even"
3. Write an R Program to check if the given Number is a Prime Number.
num = as.integer(readline(prompt = "Enter a number: "))
# num = 15
isPrime = 0
if (num > 1) {
isPrime = 1
for (i in 2: (num - 1)) {
if ((num %% i) == 0) {
isPrime = 0
break
}
}
}
if (num == 2) isPrime = 1
if (isPrime == 1) {
print(paste(num, "is a prime number"))
} else {
print(paste(num, "is not a prime number"))
}

OUTPUT

Enter a number: 15
[1] "15 is not a prime number"

Enter a number: 13
[1] "13 is a prime number"
4. Write an R Program to Find the Factorial of a Number

facto <- function(){


no = as.integer( readline(prompt=" Enter a number to find factorial : "))
fact = 1
for( i in 1:no) {
fact = fact * i
}
print(paste(" The factorial of ", no ,"is", fact ))
}
facto()

Output:

Enter a number to find factorial : 6

[1] The factorial of 6 is 720


5. Write an R Program to Make a Simple Calculator
# Program make a simple calculator that can add, subtract, multiply and divide using functions
add <- function(x, y) {
return(x + y)
}
subtract <- function(x, y) {
return(x - y)
}
multiply <- function(x, y) {
return(x * y)
}
divide <- function(x, y) {
return(x / y)
}
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = as.integer(readline(prompt="Enter choice[1/2/3/4]: "))
num1 = as.integer(readline(prompt="Enter first number: "))
num2 = as.integer(readline(prompt="Enter second number: "))
operator <- switch(choice,"+","-","*","/")
result <- switch(choice, add(num1, num2), subtract(num1, num2), multiply(num1, num2),
divide(num1, num2))
print(paste(num1, operator, num2, "=", result))

Output

[1] "Select operation."


[1] "1.Add"
[1] "2.Subtract"
[1] "3.Multiply"
[1] "4.Divide"
Enter choice[1/2/3/4]: 4
Enter first number: 20
Enter second number: 4
[1] "20 / 4 = 5"
6. Write an R Program to Find the Fibonacci sequence Using Recursive Function
# Program to display the Fibonacci sequence up to n-th term using recursive functions
recurse_fibonacci <- function(n) {
if(n <= 1) {
return(n)
} else {
return(recurse_fibonacci(n-1) + recurse_fibonacci(n-2))
}
}
# take input from the user
nterms = as.integer(readline(prompt="How many terms? "))
# check if the number of terms is valid
if(nterms <= 0) {
print("Plese enter a positive integer")
} else {
print("Fibonacci sequence:")
for(i in 0:(nterms-1)) {
print(recurse_fibonacci(i))
}
}

Output
How many terms? 9
[1] "Fibonacci sequence:"
[1] 0
[1] 1
[1] 1
[1] 2
[1] 3
[1] 5
[1] 8
[1] 13
[1] 21
7. Create the following data frame, afterwards invert Sex for all individuals.
NAME AGE HEIGHT WEIGHT sex
Lilly 25 177 57 F

Raja 32 187 77 M

Sundar 30 165 62 M
Ramya 44 160 58 F
Rakesh 39 170 69 M

Name <- c("Lilly", "Raja", "Sundar", "Ramya", "Rakesh”)


Age <- c(25, 31, 23, 52, 76, 49, 26)
Height <- c(177, 163, 190, 179, 163, 183, 164)
Weight <- c(57, 69, 83, 75, 70, 83, 53)
Sex <- as.factor(c("F", "F", "M", "M", "F", "M", "F"))
df <- data.frame (row.names = Name, Age, Height, Weight, Sex)

levels(df$Sex)

OUTPUT

[1] "F" "M"

levels(df$Sex) <- c("M","F")

df

## Age Height Weight Sex

## Lilly 25 177 57 F
## Raja 31 163 69 M
## Sundar 52 179 75 M
## Ramya 76 163 70 F
## Rakesh 49 183 83 M
8. Write an R Program to create a Matrix from a Vector using dim() function, cbind() function and
rbind().

> mat1.data <- c(1,2,3,4,5,6,7,8,9)

> mat1 <- matrix(mat1.data,nrow=3,ncol=3,byrow=TRUE)

> mat1

mat2.data <- c(10,11,12,13,14,15,16,17,18)


> mat2 <- matrix(mat2.data,nrow=3)
> mat2

> mat3.data1 <- c(1,2,3)


> mat3.data2 <- c(4,5,6)
> mat3.data3 <- c(7,8,9)
> mat3 <- cbind(mat3.data1,mat3.data2,mat3.data3)
> mat3
> mat5 <- c(2,3,5,9)
> mat5

> dim(mat5) <- c(2,2)


> mat5
9. Write an R Program to implement data visualization with ggplot2
# Installing the package
install.packages("dplyr")

# Loading package
library(dplyr)

# Summary of dataset in package


summary(mtcars)
Output:
mpg cyl disp hp
Min. :10.40 Min. :4.000 Min. : 71.1 Min. : 52.0
1st Qu.:15.43 1st Qu.:4.000 1st Qu.:120.8 1st Qu.: 96.5
Median :19.20 Median :6.000 Median :196.3 Median :123.0
Mean :20.09 Mean :6.188 Mean :230.7 Mean :146.7
3rd Qu.:22.80 3rd Qu.:8.000 3rd Qu.:326.0 3rd Qu.:180.0
Max. :33.90 Max. :8.000 Max. :472.0 Max. :335.0
drat wt qsec vs
Min. :2.760 Min. :1.513 Min. :14.50 Min. :0.0000
1st Qu.:3.080 1st Qu.:2.581 1st Qu.:16.89 1st Qu.:0.0000
Median :3.695 Median :3.325 Median :17.71 Median :0.0000
Mean :3.597 Mean :3.217 Mean :17.85 Mean :0.4375
3rd Qu.:3.920 3rd Qu.:3.610 3rd Qu.:18.90 3rd Qu.:1.0000
Max. :4.930 Max. :5.424 Max. :22.90 Max. :1.0000

# Adding size
ggplot(data = mtcars,
aes(x = hp, y = mpg, size = disp)) + geom_point()

# Adding color and shape


ggplot(data = mtcars,
aes(x = hp, y = mpg, col = factor(cyl),
shape = factor(am))) +
geom_point()

# Histogram plot
ggplot(data = mtcars, aes(x = hp)) +
geom_histogram(binwidth = 5)
10. Write an R Program to plot the bar chart and pie chart on sample data

# Create data for the graph.


x <- c(21, 62, 10, 53)
labels <- c("London", "New York", "Singapore", "Mumbai")

# Give the chart file a name.


png(file = "city.png")

# Plot the chart.


pie(x,labels)

# Save the file.


dev.off()
11. Write an R Program to create and access a Data Frame like a List

12. # create a data frame


13. dataframe1 <- data.frame (
14. Name = c("Juan", "Alcaraz"),
15. Age = c(22, 15)
16. )
17.
18. # create another data frame
19. dataframe2 <- data.frame (
20. Name = c("Yiruma", "Bach", "Ludovico"),
21. Age = c(46, 89, 72)
22. )
23.
24. # make a list of dataframe1 and dataframe2
25. print(list(dataframe1, dataframe2))

[[1]]
Name Age
1 Juan 22
2 Alcaraz 15

[[2]]
Name Age
1 Yiruma 46
2 Bach 89
3 Ludovico 72

list(dataframe1, dataframe2)

You might also like