0% found this document useful (0 votes)
5 views24 pages

R Program Code Formatted

The document provides a comprehensive overview of various R programming concepts, including data types, reading and writing data, database interactions, date handling, factors, subsetting, character manipulation, data aggregation, reshaping data, and statistical analysis techniques. It covers practical examples and code snippets for each topic, demonstrating how to perform operations like regression, ANOVA, and logistic regression. Additionally, it includes sections on advanced data handling, survival analysis, and nonlinear curve fitting.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views24 pages

R Program Code Formatted

The document provides a comprehensive overview of various R programming concepts, including data types, reading and writing data, database interactions, date handling, factors, subsetting, character manipulation, data aggregation, reshaping data, and statistical analysis techniques. It covers practical examples and code snippets for each topic, demonstrating how to perform operations like regression, ANOVA, and logistic regression. Additionally, it includes sections on advanced data handling, survival analysis, and nonlinear curve fitting.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

DATA IN R
Code:
num_val <- 99.5
cat("Numeric:", num_val, "| Type:", typeof(num_val), "\n")
char_val <- "Anna University"
cat("Character:", char_val, "\n")
log_val <- FALSE
cat("Logical:", log_val, "\n")
vec <- c(5, 15, 25, 35)
cat("Vector:", vec, "\n")
mat <- matrix(seq(1,9), nrow=3, ncol=3)
print(mat)
arr <- array(seq(1,8), dim=c(2,2,2))
print(arr)
my_list <- list(ID=10, Name="Ravi", Scores=c(70,80,90))
print(my_list)
df <- [Link](ID=1:3, Name=c("Ram","Sam","Tam"),
Score=c(91,85,78))
print(df)
dept <- factor(c("CSE","ECE","ECE","CSE"))
print(dept)
print(levels(dept))
2. READING AND WRITING DATA
Code:
staff <- [Link](
ID = c(1, 2, 3),
Name = c("Priya", "Kiran", "Mani"),
Salary = c(40000, 55000, 48000)
)
[Link](staff, file="staff_data.csv", [Link]=FALSE)
cat("Written to staff_data.csv\n")
read_back <- [Link]("staff_data.csv", stringsAsFactors=FALSE)
print(read_back)
[Link](staff, file="staff_data.txt", sep="\t", [Link]=FALSE)
cat("Written to staff_data.txt\n")
read_txt <- [Link]("staff_data.txt", header=TRUE, sep="\t")
print("Imported TXT Data:")
print(read_txt)
3. R AND DATABASES
Code:
emp_db <- [Link](
ID = c(201, 202, 203),
Name = c("Arun", "Bala", "Charu"),
Dept = c("IT", "HR", "Finance")
)
[Link](emp_db, "emp_db.csv", sep=",", [Link]=FALSE,
[Link]=TRUE)
db <- [Link]("emp_db.csv", sep=",", header=TRUE)
cat("Original Data:\n"); print(db)
new_rec <- [Link](ID=204, Name="Devi", Dept="IT")
db <- rbind(db, new_rec)
cat("\nAfter Insert:\n"); print(db)
db$Dept[db$Name == "Bala"] <- "Finance"
cat("\nAfter Update (Bala Dept Changed):\n"); print(db)
db <- db[db$Name != "Charu", ]
cat("\nAfter Deletion (Charu Removed):\n"); print(db)
[Link](db, "emp_db.csv", sep=",", [Link]=FALSE,
[Link]=TRUE)
4. DATES
Code:
today <- [Link]()
print("Today's Date:"); print(today)
join_date <- [Link]("2022-06-15")
print("Join Date:"); print(join_date)
formatted <- format(today, "%d-%B-%Y")
print("Formatted Date:"); print(formatted)
yr <- format(join_date, "%Y")
mn <- format(join_date, "%m")
dy <- format(join_date, "%d")
print(paste("Year:", yr))
print(paste("Month:", mn))
print(paste("Day:", dy))
days_worked <- today - join_date
print("Days Worked:"); print(days_worked)
now <- [Link]()
print("Current Date and Time:"); print(now)
5. FACTORS
Code:
sizes <- c("M", "L", "S", "XL", "M", "S", "L", "M")
size_factor <- factor(sizes)
print("Size Factor:"); print(size_factor)
print("Levels of size factor:"); print(levels(size_factor))
print("Number of levels:"); print(nlevels(size_factor))
size_ordered <- factor(sizes, levels=c("S","M","L","XL"),
ordered=TRUE)
print("Ordered Size Factor:"); print(size_ordered)
print("Summary of Size Factor:"); print(summary(size_factor))
6. SUBSETTING
Code:
vec <- c(100, 200, 300, 400, 500)
cat("First 3 elements:", head(vec, 3), "\n")
cat("Elements > 250:", vec[vec > 250], "\n")
mat <- matrix(1:9, nrow=3)
cat("Element at row 1, col 3:", mat[1,3], "\n")
cat("Second column:", mat[,2], "\n")
mylist <- list(city="Chennai", pin=600001, pop=c(10,12,14))
cat("Access by name:", mylist$city, "\n")
cat("Second pop value:", mylist$pop[2], "\n")
df <- [Link](ID=1:4, Name=c("Raj","Mia","Leo","Zoe"),
Marks=c(88,72,95,60))
cat("Name of 2nd student:", df$Name[2], "\n")
cat("Students with Marks > 80:\n")
print(df[df$Marks > 80, ])
7. CHARACTER MANIPULATION
Code:
str1 <- " Hello"
str2 <- "World "
cat("Concatenated (paste):", paste(str1, str2), "\n")
cat("Concatenated (paste0):", paste0(trimws(str1), trimws(str2)),
"\n")
cat("Uppercase:", toupper(str1), "\n")
cat("Lowercase:", tolower(str2), "\n")
cat("Substring from str1 (3 to 7):", substr(str1, 3, 7), "\n")
sentence <- "R language is excellent!"
cat("Original sentence:", sentence, "\n")
cat("After replacement:", gsub("excellent","powerful",sentence),
"\n")
cat("Trimmed str1:", trimws(str1), "\n")
cat("Trimmed str2:", trimws(str2), "\n")
text <- "The sun rises in the east"
cat("Is 'sun' present?:", grepl("sun", text), "\n")
8. DATA AGGREGATION
Code:
df <- [Link](
Branch = factor(c("CSE","ECE","CSE","ECE")),
Subject = factor(c("Maths","Physics","Maths","Physics")),
Marks = c(88, 76, 92, 84)
)
agg_marks <- aggregate(Marks ~ Branch, data=df, FUN=mean)
print(agg_marks)
subject_count <- table(df$Subject)
print(subject_count)
marks_dist <- [Link](table(cut(df$Marks, breaks=c(0,80,90,100))))
print(marks_dist)
9. RESHAPING DATA BASICS
Code:
wide_data <- [Link](
Student = c("Arun", "Bala", "Charu"),
Tamil_2023 = c(88, 82, 90),
English_2023 = c(85, 80, 92),
Tamil_2024 = c(91, 85, 94),
English_2024 = c(89, 83, 95)
)
long_data <- reshape(wide_data, direction="long",
varying=2:5, sep="_", idvar="Student")
wide_restored <- reshape(long_data, direction="wide",
timevar="time", idvar="Student")
list(Original=wide_data, Long=long_data, Restored=wide_restored)
10. THE R ENVIRONMENT
Code:
a <- 100
b <- c(2, 4, 6)
df <- [Link](X=c("P","Q"), Y=c(10,20))
print("Objects in Environment:"); print(ls())
print("Current Working Directory:"); print(getwd())
print("Structure of df:"); print(str(df))
rm(a)
print("Objects after removing a:"); print(ls())
rm(list=ls())
print("All objects cleared.")
11. PROBABILITY AND DISTRIBUTIONS
Code:
x <- seq(-4, 4, by=0.1)
y <- dnorm(x, mean=0, sd=1)
plot(x, y, type="l", col="blue", main="Normal Distribution")
x2 <- 0:20
y2 <- dbinom(x2, size=20, prob=0.4)
barplot(y2, [Link]=x2, col="purple", main="Binomial Distribution")
x3 <- 0:10
y3 <- dpois(x3, lambda=5)
barplot(y3, [Link]=x3, col="orange", main="Poisson Distribution")
12. DESCRIPTIVE STATISTICS AND GRAPHICS
Code:
data <- c(34, 56, 47, 62, 38, 74, 51, 43, 68, 55)
mean(data)
median(data)
sd(data)
var(data)
summary(data)
hist(data, col="coral", main="Histogram")
boxplot(data, col="lightyellow", main="Boxplot")
plot(data, type="o", col="darkgreen", main="Line Plot")
13. ONE- AND TWO-SAMPLE TESTS
Code:
data <- c(58, 62, 55, 60, 57, 63, 59)
[Link](data, mu=60)
groupA <- c(45, 47, 46, 48, 44)
groupB <- c(52, 54, 53, 55, 51)
[Link](groupA, groupB)
pre <- c(130, 125, 140, 135)
post <- c(118, 115, 128, 122)
[Link](pre, post, paired=TRUE)
14. REGRESSION AND CORRELATION
Code:
x <- c(2, 4, 6, 8, 10)
y <- c(5, 7, 8, 9, 11)
cor(x, y)
model <- lm(y ~ x)
summary(model)
plot(x, y)
abline(model, col="blue")
15. ANALYSIS OF VARIANCE AND THE KRUSKAL-WALLIS TEST
Code:
groupA <- c(5, 7, 6)
groupB <- c(10, 12, 11)
groupC <- c(15, 14, 16)
data <- [Link](
weight = c(groupA, groupB, groupC),
diet = factor(rep(c("A","B","C"), each=3))
)
anova_result <- aov(weight ~ diet, data=data)
summary(anova_result)
[Link](weight ~ diet, data=data)
16. TABULAR DATA
Code:
students <- [Link](
RollNo = c(201, 202, 203, 204),
Name = c("Kavya","Lokesh","Meena","Naveen"),
Physics = c(80, 88, 75, 92),
Chemistry = c(85, 79, 82, 90),
Biology = c(78, 84, 80, 88)
)
print("Student Marksheet:")
print(students)
17. POWER AND THE COMPUTATION OF SAMPLE SIZE
Code:
effect_size <- 0.5
power <- 0.80
alpha <- 0.05
sample_size <- [Link](
power = power,
delta = effect_size,
sd = 1,
[Link] = alpha,
type = "[Link]",
alternative = "[Link]"
)$n
cat("Required sample size (one sample, approx):",
ceiling(sample_size), "\n")
18. ADVANCED DATA HANDLING
Code:
data <- [Link](
Name = c("Siva","Tara","Uma","Vimal","Wini"),
Team = c("Dev","QA","Dev","QA","Dev"),
Score = c(72000, 61000, 80000, 58000, 75000)
)
high_score <- data[data$Score > 65000, ]
print("Employees with high score:"); print(high_score)
sorted_data <- data[order(-data$Score), ]
print("Sorted by score (descending):"); print(sorted_data)
team_avg <- aggregate(Score ~ Team, data=data, FUN=mean)
print("Average score by team:"); print(team_avg)
19. MULTIPLE REGRESSION
Code:
hours <- c(5, 10, 15, 20, 25)
tutors <- c(1, 2, 2, 3, 3)
score <- c(40, 55, 65, 78, 88)
data <- [Link](score, hours, tutors)
model <- lm(score ~ hours + tutors, data=data)
summary(model)
20. LINEAR MODELS
Code:
x <- c(3, 6, 9, 12, 15)
y <- c(6, 12, 18, 24, 30)
model <- lm(y ~ x)
summary(model)
21. LOGISTIC REGRESSION
Code:
age <- c(25, 35, 45, 55, 65)
disease <- c(0, 0, 1, 1, 1)
model <- glm(disease ~ age, family=binomial)
summary(model)
22. SURVIVAL ANALYSIS
Code:
library(survival)
time <- c(3, 7, 11, 18, 22)
status <- c(1, 0, 1, 1, 0)
surv_obj <- Surv(time, status)
fit <- survfit(surv_obj ~ 1)
summary(fit)
plot(fit)
23. RATES AND POISSON REGRESSION
Code:
visits <- c(3, 5, 7, 9, 12)
ad_spend <- c(2, 3, 4, 5, 6)
model <- glm(visits ~ ad_spend, family=poisson)
summary(model)
24. NONLINEAR CURVE FITTING
Code:
x <- 1:5
y <- c(1.8, 5.2, 9.7, 16.3, 25.1)
nls_model <- nls(y ~ a * x^b, start=list(a=1, b=1.5))
summary(nls_model)

You might also like