Hello world in R

create variables to store data

x<-5

create arrays

my_vector <- c(1, 2, 3)

create data frames aka tables

my_df <- data.frame(Name=c("John", "Jane"), Age=c(25, 30))

conditional controls

if (x>2) {
  # code to be executed if the condition is TRUE
  print("yes x is greater than 2")
} else {
  # code to be executed if the condition is FALSE
  print("yes x is greater than 2")
}
## [1] "yes x is greater than 2"

functions in R

my_function <- function(arg1, arg2) {
  # code here
  return(result)
}

installing and using libraries

install.packages("package_name")
library(package_name)

for Data Visualization ✨ install

to read a csv file

read.csv("file name")

for more help

help(function_name)
## No documentation for 'function_name' in specified packages and libraries:
## you could try '??function_name'

or go just chatGPT it


Central Tendencies

Mean

my_vector <- c(1, 2, 3, 4, 5)
mean_value <- mean(my_vector)
print(mean_value)
## [1] 3

Median

my_vector <- c(1, 2, 3, 4, 5)
median_value <- median(my_vector)
print(median_value)
## [1] 3

Range

range_value <- range(my_vector)
print(range_value)
## [1] 1 5

standard deviation

sd_value <- sd(my_vector)
print(sd_value)
## [1] 1.581139

variance

var_value <- var(my_vector)
print(var_value)
## [1] 2.5

quantiles

quantiles <- quantile(my_vector)
print(quantiles)
##   0%  25%  50%  75% 100% 
##    1    2    3    4    5

summary

summary_stats <- summary(my_vector)
print(summary_stats)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##       1       2       3       3       4       5

Sample data (replace this with your own data)

my_data <- c(23, 25, 27, 28, 22, 24, 26, 30, 21, 29)

Calculate the 95% confidence interval

confidence_interval <- t.test(my_data)$conf.int
print(confidence_interval)
## [1] 23.33415 27.66585
## attr(,"conf.level")
## [1] 0.95

another manual method to change confidence intervals

# Sample data
my_data <- c(25, 30, 35, 40, 45)

# Sample mean, standard deviation, and sample size
mean_value <- mean(my_data)
std_dev <- sd(my_data)
sample_size <- length(my_data)

# Calculate standard error
standard_error <- std_dev / sqrt(sample_size)

# Set the confidence level
confidence_level <- 0.90

# Calculate the critical value for a normal distribution
critical_value <- qnorm((1 + confidence_level) / 2)

# Calculate the margin of error
margin_of_error <- critical_value * standard_error

# Calculate the confidence interval
confidence_interval <- c(mean_value - margin_of_error, mean_value + margin_of_error)

# Print the result
cat("90% Confidence Interval: [", confidence_interval[1], ",", confidence_interval[2], "]")
## 90% Confidence Interval: [ 29.18456 , 40.81544 ]