0% found this document useful (0 votes)
9 views27 pages

R Programming

The document provides a series of R programming exercises, including finding factors of a number, checking for prime numbers, generating even numbers, calculating GCD, producing Fibonacci sequences, and performing string manipulations. Each section includes a program, output examples, and a result statement indicating successful execution. Additionally, it covers data frame operations such as connecting data frames using rbind() and cbind().

Uploaded by

mp0630262
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)
9 views27 pages

R Programming

The document provides a series of R programming exercises, including finding factors of a number, checking for prime numbers, generating even numbers, calculating GCD, producing Fibonacci sequences, and performing string manipulations. Each section includes a program, output examples, and a result statement indicating successful execution. Additionally, it covers data frame operations such as connecting data frames using rbind() and cbind().

Uploaded by

mp0630262
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

1a.

FIND FACTORS OF A NUMBER

AIM:

To write a R programming to find factors of a number.

PROGRAM:

# Get the number from the user

num <- [Link](readline(prompt = "Enter a number: "))

# Loop to find and print the factors

for (i in 1:num) {

if (num %% i == 0) {

print(i) # Print the factor

Step 1: Open RStudio

 Once RStudio is installed, open it from your Start menu (Windows)

Step 2: Create a New R Script

1. Create a New Script:


o In RStudio, go to the top menu and click File > New File > R Script.
2. Enter Your Code:
o Copy the R code you have (or write it in the script editor) into the newly opened script.

Step 3: Save the Script:

 Save the script by clicking File > Save, or pressing Ctrl + S. Choose a name and save it as an .R
file (e.g., check_prime.R).

Option 1: Run the Entire Script

1. Click the Run button (green triangle) in the top-right corner of the script editor.
2. Alternatively, press Ctrl + Shift + Enter on your keyboard to run the entire script.

Option 2: Run Selected Lines of Code

 You can highlight just the part of the code you want to run, and then click Run or press Ctrl +
Enter.
OUTPUT

Enter a number: 45

[1] 1
[1] 3
[1] 5
[1] 9
[1] 15
[1] 45

# Input: Read the number from the user

num <- [Link](readline(prompt = "Enter a number: "))

# Loop through numbers from 1 to num

cat("Factors of", num, "are: ")

for (i in 1:num) {

if (num %% i == 0) {

cat(i, " ") # Print each factor

cat("\n") # Print newline after factors

OUTPUT

Enter a number: 45

Factors of 45 are: 1 3 5 9 15 45

RESULT:

Thus above program find factors of a number executed successfully.


1.b PRIME NUMBER

AIM:

To write a R program to check if the given number is a prime number.

PROGRAM:

Simple R Program to Check if a Number is Prime:

# Get the number from the user

num <- [Link](readline(prompt = "Enter a number: "))

# Check if the number is prime

if (num <= 1) {

cat(num, "is not a prime number.\n")

} else if (all(num %% 2:floor(sqrt(num)) != 0)) {

cat(num, "is a prime number.\n")

} else {

cat(num, "is not a prime number.\n")

OUTPUT

Enter a number: 7

7 is a prime number.

Enter a number: 49

49 is not a prime number.

RESULT:

Thus above program check the number is prime or not executed successfully.
Ex2a EVEN NUMBERS FROM 1 TO N

AIM:

To write a R program to find list of even numbers from 1 to n using R loops.

PROGRAM

Simple R Program to Find Even Numbers from 1 to n:

# Get the value of n from the user

n <- [Link](readline(prompt = "Enter a number: "))

# Loop through numbers from 1 to n

for (i in 1:n) {

if (i %% 2 == 0) { # Check if the number is even

print(paste("Even number is;",i)) # Print the even number

OUTPUT:

Enter a number: 20

[1] "Even number is; 2"

[1] "Even number is; 4"

[1] "Even number is; 6"

[1] "Even number is; 8"

[1] "Even number is; 10"

[1] "Even number is; 12"

[1] "Even number is; 14"

[1] "Even number is; 16"

[1] "Even number is; 18"

[1] "Even number is; 20"

RESULT:

Thus above program find list of even numbers from 1 to n executed successfully.
Ex2b GCD OF TWO NUMBERS

AIM:

To write a R program to find GCD of two numbers.

PROGRAM:

# Get two numbers from the user

num1 <- [Link](readline(prompt = "Enter the first number: "))

num2 <- [Link](readline(prompt = "Enter the second number: "))

# Calculate GCD using Euclidean algorithm

while (num2 != 0) {

temp <- num2

num2 <- num1 %% num2

num1 <- temp

# Print the result

cat("The GCD is", num1, "\n")

OUTPUT

Enter the first number: 24

Enter the second number: 36

The GCD is 12

Enter the first number: 101

Enter the second number: 10

The GCD is 1

RESULT:

Thus above program to find GCD of two numbers executed successfully.


Ex3 FIBONACCI SEQUENCE USING RECURSIVE FUNCTION

AIM:

To write a R program to find GCD of two numbers.

PROGRAM:

# Recursive function to calculate the nth Fibonacci number

fibonacci <- function(n) {

if (n == 0) {

return(0) # Base case: F(0) = 0

} else if (n == 1) {

return(1) # Base case: F(1) = 1

} else {

return(fibonacci(n-1) + fibonacci(n-2)) # Recursive call

# Get the value of n from the user

n <- [Link](readline(prompt = "Enter the number of terms: "))

# Print the Fibonacci sequence up to the nth term

cat("Fibonacci Sequence: ")

for (i in 0:(n-1)) {

cat(fibonacci(i), " ")

cat("\n")

EX3

# Recursive function to calculate the nth Fibonacci number

fibonacci <- function(n) {

if (n <= 1) {

return(n) # Base case: F(0) = 0, F(1) = 1

} else {
return(fibonacci(n - 1) + fibonacci(n - 2)) # Recursive call

# Get the number of terms from the user

n <- [Link](readline(prompt = "Enter the number of terms: "))

# Print the Fibonacci sequence

cat("Fibonacci Sequence: ")

for (i in 0:(n - 1)) {

cat(fibonacci(i), " ")

cat("\n")

Enter the number of Fibonacci terms: 10

Fibonacci sequence:

0 1 1 2 3 5 8 13 21 34

RESULT:

Thus above program to Fibonacci sequence using recursive function executed successfully.
Ex 4 SQUARES OF NUMBERS IN SEQUENCE ORDER

AIM:

To write a R program in squares of numbers in sequence order.

PROGRAM:

# Function to print squares of numbers in sequence

print_squares <- function(n) {

for (i in 1:n) {

cat(i^2, " ")

cat("\n")

# Example usage: Print squares of numbers from 1 to n

n <- 10 # Set the number of terms

print_squares(n)

OUTPUT

1 4 9 16 25 36 49 64 81 100

# Function to print squares of numbers in sequence

print_squares <- function(n) {

for (i in 1:n) {

cat(i^2, " ")

cat("\n")

}
# Get the input number from the user

n <- [Link](readline(prompt = "Enter a number: "))

# Call the function to print squares of numbers from 1 to n

print_squares(n)

OUTPUT

Enter a number: 5

1 4 9 16 25

RESULT:

Thus above program to squares of numbers in sequence order executed successfully.


Ex 5 STRING MANIPULATION FUNCTIONS IN R

AIM:

To write a R program for String Manipulation functions .

PROGRAM:

# 1. Concatenate Strings

concat_strings <- function(...){

return(paste(...))

# 2. Find the Length of a String

string_length <- function(str) {

return(nchar(str))

# 3. Convert a String to Uppercase

convert_to_upper <- function(str) {

return(toupper(str))

# 4. Replace a Substring

replace_substring <- function(str, old, new) {

return(gsub(old, new, str))

# 5. Check if String Contains Substring

contains_substring <- function(str, substring) {

return(grepl(substring, str))

}
# Example usage:

cat("Concatenate 'Hello' and 'World': ", concat_strings("Hello", "World"), "\n")

cat("Length of 'Hello': ", string_length("Hello"), "\n")

cat("Uppercase of 'hello': ", convert_to_upper("hello"), "\n")

cat("Replace 'R' with 'Python' in 'I love R': ", replace_substring("I love R", "R", "Python"), "\n")

cat("Does 'R programming' contain 'pro'? ", contains_substring("R programming", "pro"), "\n")

OUTPUT:

Concatenate 'Hello' and 'World': Hello World

Length of 'Hello': 5

Uppercase of 'hello': HELLO

Replace 'R' with 'Python' in 'I love R': I love Python

Does 'R programming' contain 'pro'? TRUE

RESULT:

Thus above program to in squares of numbers in sequence order executed successfully


Ex 6 VECTOR

AIM:

To write a R program for vectors.

PROGRAM:

# (a) Create a vector v1 with elements 1 to 10

v1 <- 1:10

cat("Vector v1: ", v1, "\n")

# (b) Add 2 to every element of the vector v1

v1_plus_2 <- v1 + 2

cat("v1 after adding 2 to every element: ", v1_plus_2, "\n")

# (c) Divide every element in v1 by 5

v1_div_5 <- v1 / 5

cat("v1 after dividing every element by 5: ", v1_div_5, "\n")

# (d) Create a vector v2 with elements from 11 to 20

v2 <- 11:20

cat("Vector v2: ", v2, "\n")

# Now add v1 to v2

v1_plus_v2 <- v1 + v2

cat("v1 + v2: ", v1_plus_v2, "\n")

OUTPUT:

Vector v1: 1 2 3 4 5 6 7 8 9 10

v1 after adding 2 to every element: 3 4 5 6 7 8 9 10 11 12

v1 after dividing every element by 5: 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2

Vector v2: 11 12 13 14 15 16 17 18 19 20

v1 + v2: 12 14 16 18 20 22 24 26 28 30

RESULT:

Thus above program for vectors executed successfully


PART B

Ex1a CONNECT DATA FRAMES

AIM:

To write a R program to connect data frames.

PROGRAM:

# Create a DataFrame

my_data <- [Link](

Name = c("Alice", "Bob", "Charlie", "David"),

Age = c(25, 30, 35, 40),

City = c("New York", "Los Angeles", "Chicago", "Houston")

# Display the DataFrame

print("Data Frame:")

print(my_data)

# Accessing DataFrame like a List:

# You can access columns by using the `$` sign or by using double square brackets `[[ ]]`.

# 1. Access the 'Name' column using the $ operator

print("Names:")

print(my_data$Name)

# 2. Access the 'Age' column using the $ operator

print("Ages:")

print(my_data$Age)

# 3. Access the 'City' column using the $ operator

print("Cities:")

print(my_data$City)

# 4. Access a column using double square brackets (similar to list indexing)

print("Accessing the 'Age' column using [[ ]]")

print(my_data[["Age"]])
# 5. Accessing multiple columns by creating a list-like structure:

# For example, extracting 'Name' and 'City' columns together

subset_data <- my_data[c("Name", "City")]

print("Subset of Data (Name and City columns):")

print(subset_data)

OUTPUT:

Data Frame:

Name Age City

1 Alice 25 New York

2 Bob 30 Los Angeles

3 Charlie 35 Chicago

4 David 40 Houston

Names:

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

Ages:

[1] 25 30 35 40

Cities:

[1] "New York" "Los Angeles" "Chicago" "Houston"

Accessing the 'Age' column using [[ ]]:

[1] 25 30 35 40

Subset of Data (Name and City columns):

Name City

1 Alice New York

2 Bob Los Angeles

3 Charlie Chicago

4 David Houston
SIMPLE PROGRAM:

# Create a DataFrame

my_data <- [Link](

Name = c("Alice", "Bob", "Charlie"),

Age = c(25, 30, 35)

# Access columns like a list

# Access 'Name' column

print(my_data$Name)

# Access 'Age' column

print(my_data$Age)

OUTPUT:

[1] "Alice" "Bob" "Charlie"

[1] 25 30 35

RESULT:

Thus above program for connect data frames executed successfully


Ex1b CONNECT DATA FRAMES USING RBIND()&CBIND

AIM:

To write a R program to connect data frames using rbind) and cbind()

PROGRAM:

# Create two DataFrames to demonstrate column and row binding

df1 <- [Link](

Name = c("Alice", "Bob"),

Age = c(25, 30)

df2 <- [Link](

City = c("New York", "Los Angeles")

# Display the original data frames

print("Original DataFrame 1:")

print(df1)

print("Original DataFrame 2:")

print(df2)

# Column binding using cbind() (adds columns to df1)

df_column_combined <- cbind(df1, df2)

# Display the column-bound DataFrame

print("Column-Bound DataFrame (using cbind()):")

print(df_column_combined)

# Create another DataFrame for row binding

df3 <- [Link](

Name = c("Charlie", "David"),

Age = c(35, 40),

City = c("Chicago", "Houston")


)

# Display the third DataFrame

print("DataFrame 3 (for row binding):")

print(df3)

# Row binding using rbind() (adds rows to df1)

df_row_combined <- rbind(df1, df3)

# Display the row-bound DataFrame

print("Row-Bound DataFrame (using rbind()):")

print(df_row_combined)

OUTPUT:

Original DataFrame 1:

Name Age

1 Alice 25

2 Bob 30

Original DataFrame 2:

City

1 New York

2 Los Angeles

Column-Bound DataFrame (using cbind()):

Name Age City

1 Alice 25 New York

2 Bob 30 Los Angeles

DataFrame 3 (for row binding):

Name Age City

1 Charlie 35 Chicago

2 David 40 Houston
Row-Bound DataFrame (using rbind()):

Name Age City

1 Alice 25 New York

2 Bob 30 Los Angeles

3 Charlie 35 Chicago

4 David 40 Houston

SIMPLE PROGRAM:

# Create two simple data frames

df1 <- [Link](Name = c("Alice", "Bob"))

df2 <- [Link](Age = c(25, 30))

# Column bind (combine by adding columns)

df_combined_columns <- cbind(df1, df2)

print("Column Bound DataFrame:")

print(df_combined_columns)

# Create another simple data frame for row binding

df3 <- [Link](Name = c("Charlie", "David"), Age = c(35, 40))

# Row bind (combine by adding rows)

df_combined_rows <- rbind(df1, df3)

print("Row Bound DataFrame:")

print(df_combined_rows)
OUTPUT:

Column Bound DataFrame:

Name Age

1 Alice 25

2 Bob 30

Row Bound DataFrame:

Name Age

1 Alice 25

2 Bob 30

3 Charlie 35

4 David 40

RESULT:

Thus above program for connect data frames using rbind() & cbind() executed
successfully.
Ex2 CREATE ACCESS & MODIFY ITS COMPONENTS OF A FACTOR

AIM:

To write a R program to create a access & modify components of factors.

PROGRAM:

# Create a Factor

my_factor <- factor(c("Low", "High", "Medium", "Low", "High"))

print("Original Factor:")

print(my_factor)

# Access the levels (unique values) of the factor

print("Levels of the factor:")

print(levels(my_factor))

# Modify an element of the factor

my_factor[1] <- "Medium"

print("Modified Factor:")

print(my_factor)

OUTPUT:

Original Factor:

[1] Low High Medium Low High

Levels: High Low Medium

Levels of the factor:

[1] "High" "Low" "Medium"

Modified Factor:

[1] Medium High Medium Low High

Levels: High Low Medium

RESULT:

Thus above program to create a access & modify components of factors executed successfully.
Ex3 READ A CSV FILE AND ANALYZE THE DATA IN THE FILE IN R

AIM:

To write a R program to read a csv file and analyze the data in the file in R.

PROGRAM:

# Step 1: Read the CSV file

data <- [Link]("[Link]")

# Step 2: Display the first few rows of the data

print("First few rows of the data:")

print(head(data))

# Step 3: Display the summary of the data

print("Summary of the data:")

print(summary(data))

OUTPUT:

First few rows of the data:

Name Age

1 Alice 25

2 Bob 30

3 Charlie 35

Summary of the data:

Name Age

Length:3 Min. :25

Class :character 1st Qu.:27.5

Mode :character Median :30

Mean :30

3rd Qu.:32.5

Max. :35

RESULT:

Thus above program to read a csv file and analyze the data in the file in R

executed successfully.
Ex4a PIE CHART
AIM:

To write a R program to create a pie chart.

PROGRAM:

# Data for the pie chart

slices <- c(30, 20, 15, 35) # Values representing each slice

labels <- c("A", "B", "C", "D") # Labels for each slice

# Create the pie chart

pie(slices, labels = labels, main = "Simple Pie Chart", col = rainbow(length(slices)))

Example Output:

The pie chart will display a simple chart with slices labeled A, B, C, and D, with the corresponding sizes
of 30%, 20%, 15%, and 35%.

# Data for the pie chart

slices <- c(40, 30, 20, 10) # Values for each slice

# Create the pie chart

pie(slices, main = "Simple Pie Chart")

Sample Output:

This will display a pie chart with 4 slices, with the default colors and no labels.

RESULT:

Thus above program to create a pie chart executed successfully.


Ex4b PLOT A BAR PLOT WITH MATRIX USING R
AIM:

To write a R program to create a pie chart.

PROGRAM:

# Create a matrix

data_matrix <- matrix(c(5, 10, 15, 20, 25, 30), nrow = 3, byrow = TRUE)

# Create a bar plot from the matrix

barplot(data_matrix, beside = TRUE, col = c("red", "blue", "green"),

main = "Bar Plot from Matrix",

legend = c("Group 1", "Group 2", "Group 3"))

OUTPUT:

Sample Output:

This will create a bar plot with three groups, each containing two bars, and each group will have a
different color.

RESULT:

Thus above program to plot a bar plot with matrix using r executed successfully
Ex5 STATISTICAL ANALYSIS
AIM:

To write a R program to create a dataset and do statistical analysis on the data using R.

PROGRAM:

# Step 1: Create a dataset (data frame)

data <- [Link](

Name = c("Alice", "Bob", "Charlie", "David", "Eva"),

Age = c(25, 30, 35, 40, 22),

Score = c(88, 92, 85, 78, 95)

# Step 2: View the dataset

print("Dataset:")

print(data)

# Step 3: Statistical Analysis

# Summary of the data (mean, median, min, max, etc.)

print("Summary of the dataset:")

print(summary(data))

# Calculate the mean of the 'Age' column

print("Mean Age:")

print(mean(data$Age))

# Calculate the median of the 'Score' column

print("Median Score:")

print(median(data$Score))

# Calculate the standard deviation of the 'Score' column

print("Standard Deviation of Score:")

print(sd(data$Score))
# Calculate the variance of the 'Age' column

print("Variance of Age:")

print(var(data$Age))

# Find the correlation between 'Age' and 'Score'

print("Correlation between Age and Score:")

print(cor(data$Age, data$Score))

 Create a Dataset:

 We create a data frame data with three columns: Name, Age, and Score.

 Statistical Analysis:

 summary(data): Provides basic statistics for each column, such as the mean, median, min, and
max values for numeric columns.
 mean(): Computes the mean (average) of the Age column.
 median(): Computes the median of the Score column.
 sd(): Computes the standard deviation of the Score column, which tells you how spread out the
data is.
 var(): Computes the variance of the Age column, which measures how much the Age values vary
from the mean.
 cor(): Computes the correlation between the Age and Score columns, indicating how strongly the
two variables are related.

OUTPUT:

Dataset:

Name Age Score

1 Alice 25 88

2 Bob 30 92

3 Charlie 35 85

4 David 40 78

5 Eva 22 95
Summary of the dataset:

Name Age Score

Length:5 Min. :22.00 Min. :78.00

Class :character 1st Qu.:25.00 1st Qu.:85.00

Mode :character Median :30.00 Median :88.00

Mean :30.40 Mean :87.60

3rd Qu.:35.00 3rd Qu.:92.00

Max. :40.00 Max. :95.00

Mean Age:

[1] 30.4

Median Score:

[1] 88

Standard Deviation of Score:

[1] 6.795

Variance of Age:

[1] 34.3

Correlation between Age and Score:

[1] -0.1759
SIMPLE PROGRAM

# Create a simple dataset

data <- c(25, 30, 35, 40, 22)

# Calculate the mean

mean_value <- mean(data)

print(paste("Mean:", mean_value))

# Calculate the standard deviation

sd_value <- sd(data)

print(paste("Standard Deviation:", sd_value))

OUTPUT:

[1] "Mean: 30.4"

[1] "Standard Deviation: 6.795"

RESULT:

Thus above program to create a dataset and do statistical analysis on the


data using R executed successfully

You might also like