R - Programming BCA
R - Programming BCA
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 }
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) }