0% found this document useful (0 votes)
6 views8 pages

R Programming Basics and Examples

Uploaded by

harshanmatheesh
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)
6 views8 pages

R Programming Basics and Examples

Uploaded by

harshanmatheesh
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

R Programming

1. Create a numeric variable and print it.

x <- 10

2. Create a character variable and print it.

name <- "R Programming"

name

3. Create a logical variable and print it.

flag <- TRUE

flag

4. Create an integer variable and check its type.

a <- 15L

class(a)

5. Create two variables and print them using paste().

a <- "Data"

b <- "Science"

paste(a, b)

6. Store your name and age in variables and print them.

name <- "Alen"

age <- 22

paste("My name is", name, "and I am", age, "years old")

7. Add two numbers.

a <- 20

b <- 35

a+b

8. Calculate simple interest.


P <- 5000

R <- 7;

T <- 2

SI <- (P * R * T) / 100

SI

9. Find simple GST calculation (18%).

price <- 1200

gst <- price + (price * 0.18)

paste(“GST : “,gst)

10. Accept marks of a student and calculate percentage, average.

m1 <- [Link](readline("Enter marks out of 100: "))


m2 <- [Link](readline("Enter marks out of 100: "))
m3 <- [Link](readline("Enter marks out of 100: "))
m4 <- [Link](readline("Enter marks out of 100: "))
total <- m1+m2+m3+m4
perc <- (total/400)*100
paste(“Percentage : “,perc)
averg <- total/4
paste(“Average : “, averg)

11. Calculate EMI

loan_amount <- 500000

annual_interest_rate <- 10

loan_months <- 12

emi_amount <- (loan_amount + (loan_amount * annual_interest_rate / 100)) / loan_months

paste(“EMI Amount : “, emi_amount)

12. Check if a student passed (pass if marks ≥ 40)

student_marks <- 55
if (student_marks >= 40) {

print("Pass")

} else {

print("Fail")

13. Check if temperature is High, Medium, or Low.

temperature_celsius <- 34

if (temperature_celsius > 30) {

print("High Temperature")

} else if (temperature_celsius >= 20) {

print("Moderate Temperature")

} else {

print("Low Temperature")

14. Check if number is even or odd.

number <- 27

if (number %% 2 == 0) {

print("Even Number")

} else {

print("Odd Number")

15. Determine admission category based on marks.

score <- 88

if (score >= 90) {


print("A Grade")

} else if (score >= 75) {

print("B Grade")

} else if (score >= 60) {

print("C Grade")

} else {

print("D Grade")

16. Print numbers 1 to 10 using a for loop.

for (i in 1:10) {

print(i)

17. Sum of numbers from 1 to 50 using a loop.

total_sum <- 0

for (i in 1:50) {

total_sum <- total_sum + i

total_sum

18. Print numbers from 1 to 50 using while loop.

i <- 1

while (i <= 50) {

print(i)

i <- i + 1

}
19. Countdown from 10 to 1.

n <- 10

while (n >= 1) {

print(n)

n <- n - 1

20. Find sum of marks from a vector.

marks <- c(78, 85, 90, 67, 88)

total_marks <- 0

for (mark in marks) {

total_marks <- total_marks + mark

total_marks

21. Create a vector of 5 product prices and print them

product_prices <- c(120, 350, 499, 89, 250)

product_prices

22. Find the highest score among students.

student_scores <- c(78, 92, 85, 66, 88)

max(student_scores)

23. Find the lowest temperature recorded.

temperature_week <- c(31, 29, 28, 32, 33, 30, 27)


min(temperature_week)
24. Create a vector of 5 bills and add a service charge of ₹20 each.

restaurant_bills <- c(320, 450, 210, 600, 750)

final_bills <- restaurant_bills + 20

final_bills

25. Create a data frame of 3 students with name, age, and marks. Print the data frame.

student_data <- [Link](

student_name = c("Asha", "Rahul", "Meera"),

student_age = c(20, 21, 19),

student_marks = c(88, 76, 92)

student_data

26. Create a data frame for 4 products with price and quantity. Calculate total value (price ×
quantity).

product_data <- [Link](

product_name = c("Pen", "Book", "Bag", "Bottle"),

product_price = c(10, 80, 450, 150),

product_quantity = c(20, 10, 5, 8)

product_value <- product_data$product_price * product_data$product_quantity

product_value

27. Plot a line graph of weekly temperatures.


weekly_days <- c("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")

weekly_temperatures <- c(29, 30, 32, 31, 33, 34, 29)

plot(weekly_temperatures, type = "o", col = "blue",

main = "Weekly Temperature Trend",

xlab = "Day", ylab = "Temperature (°C)")

28. Create a bar chart of sales of 5 products.

product_names <- c("Mobile", "Laptop", "Tablet", "Headset", "Camera")

product_sales <- c(120, 75, 50, 200, 40)

barplot(product_sales, [Link] = product_names,

col = "orange", main = "Product Sales",

xlab = "Products", ylab = "Units Sold")

29. Draw a pie chart of market share.

market_share <- c(40, 25, 15, 10, 10)

company_names <- c("Brand A", "Brand B", "Brand C", "Brand D", "Others")

pie(market_share, labels = company_names,

main = "Market Share Distribution")

30. Plot a scatter plot of height vs weight.

height_cm <- c(150, 160, 165, 170, 175, 180)

weight_kg <- c(50, 55, 60, 65, 75, 80)

plot(height_cm, weight_kg,

main = "Height vs Weight",


xlab = "Height (cm)", ylab = "Weight (kg)",

col = "darkgreen", pch = 19)

31. Histogram of student marks.

student_marks <- c(45, 55, 65, 70, 72, 80, 85, 90, 91, 60, 58)

hist(student_marks, col = "lightblue",

main = "Distribution of Student Marks",

xlab = "Marks", ylab = "Frequency")

Common questions

Powered by AI

Data frames in R are crucial for handling and analyzing structured data. They store data in a tabular format, allowing for advanced manipulation and operations across rows and columns. Data frames support operations like subsetting, aggregation, and are used extensively in statistical analysis and creating complex modeling workflows, enhancing data analysis capabilities .

Loops, such as 'for' or 'while', are used in R for iterating through a sequence of values to perform operations like summation. For example, a 'for' loop like `for (i in 1:50) {total_sum <- total_sum + i}` sums numbers from 1 to 50 incrementally, adding each element to a cumulative total .

In R, a pie chart represents parts of a whole as slices of a circle, using the `pie()` function. It is significant for visualizing data to quickly display proportionate distribution among categories. For example, `pie(market_share, labels = company_names)` visually distinguishes market shares among different brands .

The EMI (Equated Monthly Installment) calculation in R involves computing the total amount repayable per month over the loan tenure. Using the formula `(loan_amount + (loan_amount * annual_interest_rate / 100)) / loan_months`, it offers insights into regular financial commitments required for loan repayment, aiding in financial planning and forecasting .

In R, you apply a service charge to each element of a vector by using vector arithmetic. Adding a fixed amount like ₹20 to each bill is performed by the expression `final_bills <- restaurant_bills + 20`, where `restaurant_bills` is a vector of individual bill amounts .

To calculate the average and percentage of a student's marks in R, obtain the total marks by summing individual scores and dividing by the number of subjects for the average. Calculate the percentage by dividing the total score by the maximum possible score, then multiply by 100. Example code is: total <- m1+m2+m3+m4; perc <- (total/400)*100; averg <- total/4 .

The paste() function in R concatenates multiple strings or variables with a default separator, which is a space. It can merge variables or text to form a single continuous output, such as in the example `paste(a, b)` where `a <- "Data"` and `b <- "Science"` results in "Data Science" .

R employs conditional statements to categorize temperature as 'High', 'Moderate', or 'Low', based on defined thresholds. The use of `if`, `else if`, and `else` statements exemplifies decision-making processes by executing different code paths based on conditions, aiding in immediate categorization and interpretation of temperature data for quick decision-making .

R determines whether a number is even or odd using the modulus operator (%%). For instance, the expression `number %% 2 == 0` checks if the number is evenly divisible by 2, identifying it as even; if not, it is odd .

To calculate and display the GST of a product in R, calculate the GST amount and add it to the original price using arithmetic. The operation `gst <- price + (price * 0.18)` adds an 18% GST to the original price, and `paste("GST : ",gst)` is used to display the result .

You might also like