Data Frames in R
A data frame in R is a two-dimensional table-like data structure where each column
contains values of one variable and each row contains one set of values from each
column. It is similar to a spreadsheet or a database table. Data frames are used for storing
data tables.
Creating a Data Frame:
You can create a data frame using the data.frame() function.
Example:
data <- data.frame(Name = c("Alice", "Bob"), Age = c(25, 30))
Accessing Data Frame:
Access specific elements using `$`, `[row, column]`, or column name.
Example:
data$Name
data[1, 2]
Assigning Column and Row Names:
Use colnames() and rownames() to assign names.
colnames(data) <- c("Person", "Years")
rownames(data) <- c("Row1", "Row2")
Binding Data Frames:
Use rbind() to bind by rows and cbind() to bind by columns.
rbind(df1, df2)
cbind(df1, df2)
Various Operations:
- Filtering: subset(data, Age > 25)
- Sorting: data[order(data$Age), ]
- Summary: summary(data)
Lists in R:
A list is a collection of elements that can be of different types.
Example:
my_list <- list(Name = "John", Age = 28, Scores = c(85, 90))
Access: my_list$Name
Control Structures in R
Control structures in R allow conditional execution of code.
If-Then:
x <- 5
if (x > 3) { print("x is greater than 3") }
If-Else:
if (x > 3) { print("x > 3") } else { print("x <= 3") }
If-Else If-Else:
if (x > 10) {...} else if (x > 3) {...} else {...}
Switch Statement:
x <- 2
switch(x, "1" = "One", "2" = "Two")
For Loop:
for (i in 1:5) { print(i) }
While Loop:
i <- 1
while (i <= 5) { print(i); i <- i + 1 }
Break and Next:
Break: Exits loop early
Next: Skips current iteration
for (i in 1:5) { if (i == 3) next; print(i) }
Functions in R
Functions in R are used to encapsulate code for reuse.
Defining a Function:
square <- function(x) { return(x^2) }
Calling a Function:
square(4) # Returns 16
Scope of Variables:
Variables inside a function are local. Global variables are outside the function.
Returning Values:
Use return(). If omitted, the last evaluated expression is returned.
add <- function(a, b) { return(a + b) }