R Tutorial
Fundamentals of R
Variables
Input and Output
Decision Making
Control Flow
Functions
Strings
Vectors
Lists
Arrays
Matrices
Factors
DataFrames
Object Oriented Programming
Error Handling
File Handling
Packages in R
Data Interfaces
Data Visualization
Statistics
Machine Learning with R
R is a powerful language for data analysis and statistical computing. Below is a brief tutorial on basic syntax in R:
1. Variables and Assignment
To assign values to variables, we use the <-
operator (though =
can be used as well):
x <- 5 y <- "Hello, World!"
2. Basic Operations
Simple mathematical operations can be performed directly:
x + 5 # 10 x * 2 # 10 x / 2 # 2.5
3. Vectors
Vectors are sequences of elements. They can be created using the c()
function:
v <- c(1, 2, 3, 4, 5)
Operations on vectors are often element-wise:
v + 2 # Adds 2 to each element
4. Functions
R has many built-in functions:
sum(v) # 15 mean(v) # 3
To define your own function:
my_function <- function(a, b) { result <- a + b return(result) }
5. Data Frames
Data frames are like tables and can be thought of as a list of vectors:
df <- data.frame( Names = c("Alice", "Bob", "Charlie"), Ages = c(25, 30, 35), Salaries = c(50000, 60000, 70000) )
You can access columns using $
:
df$Names
6. Control Structures
If-else:
if (x > 5) { print("Greater than 5") } else { print("Not greater than 5") }
For loop:
for (i in 1:5) { print(i) }
While loop:
count <- 1 while (count <= 5) { print(count) count <- count + 1 }
7. Installing and Using Packages
You can install packages using:
install.packages("package_name")
Load them with:
library(package_name)
8. Importing Data
For a CSV file:
data <- read.csv("file_path.csv")
9. Basic Plotting
A simple plot can be made with:
plot(v, type="o", col="red", main="My Plot", xlab="X", ylab="Y")
This is a very brief introduction, and there is much more to learn in R. R has extensive documentation, and there are many online resources available to help further your understanding.
How to Write a Simple R Script:
Save the following code in a file with a .R
extension, for example, myscript.R
:
# This is a simple R script # Print a message print("Hello, World!") # Perform a simple calculation result <- 5 + 3 print(result)
You can run the script using the source
function in R or by executing it in an R environment.
Variables and Assignments in R:
# Variable assignment my_variable <- 42 # Print the variable print(my_variable) # Reassign the variable my_variable <- my_variable + 10
Conditional Statements in R:
# If statement my_condition <- TRUE if (my_condition) { print("Condition is TRUE") } else { print("Condition is FALSE") }
Loops in R Programming:
For Loop:
# For loop for (i in 1:5) { print(paste("Iteration:", i)) }
While Loop:
# While loop count <- 1 while (count <= 5) { print(paste("Iteration:", count)) count <- count + 1 }