apply(X, MARGIN, FUN)
Here:
-x: an array or matrix
-MARGIN: take a value or range between 1 and 2 to define where to
apply the function:
-MARGIN=1`: the manipulation is performed on rows
-MARGIN=2`: the manipulation is performed on columns
-MARGIN=c(1,2)` the manipulation is performed on rows and columns
-FUN: tells which function to apply. Built functions like mean,
median, sum, min, max and even user-defined functions can be
applied>
m1 <- matrix(C<-(1:10),nrow=5, ncol=6)
m1
a_m1 <- apply(m1, 2, sum)
A_m1
lapply(X, FUN)
Arguments:
-X: A vector or an object
-FUN: Function applied to each element of x
movies <- c("SPYDERMAN","BATMAN","VERTIGO","CHINATOWN")
movies_lower <-lapply(movies, tolower)
str(movies_lower)
sapply(X, FUN)
Arguments:
-X: A vector or an object
-FUN: Function applied to each element of x
dt <- cars
lmn_cars <- lapply(dt, min)
smn_cars <- sapply(dt, min)
lmn_cars
smn_cars
lmxcars <- lapply(dt, max)
smxcars <- sapply(dt, max)
lmxcars
avg <- function(x) {
( min(x) + max(x) ) / 2 }
fcars <- sapply(dt, avg)
fcars
below_ave <- function(x) {
ave <- mean(x)
return(x[x < ave])
}
dt_s<- sapply(dt, below_ave)
dt_l<- lapply(dt, below_ave)
identical(dt_s, dt_l)
tapply(X, INDEX, FUN = NULL)
Arguments:
-X: An object, usually a vector
-INDEX: A list containing factor
-FUN: Function applied to each element of x
data(iris)
tapply(iris$[Link], iris$Species, median)
Q1 <- matrix(c(rep(1, 4), rep(2, 4), rep(3, 4), rep(4, 4)),4,4)
print(Q1)
Q2 <- mapply(rep,1:4,4)
print(Q2)