## General help related to functions

• we can use `?<function>` to get help and `args(function)` to get the list of arguments
• lapply is function which we use to apply some function to a list of elements
``````movies <- c("New Hope:1977", "The Empire Strikes Back:1980", "Return of the Jedi:1983")

split_movies <- strsplit(movies, split = ":")
print(split_movies)

split_movies_lower <- tolower(movies)
print(split_movies_lower)

split_movies_lapply <- lapply(movies, strsplit, split=":")
print(split_movies_lapply)

split_movies_sapply <- sapply(movies, strsplit, split=":")
print(split_movies_sapply)
``````
• Now lets apply custom functions written by us to execute with lapply
``````select_first <- function(x) {
x[1]
}
select_nth <- function(x, n) {
x[n]
}

split <- strsplit(movies, split = ":")
print(split)

split_low <- lapply(split, tolower)
print(split_low)

first_items <- lapply(split_low, select_first)
print(first_items)

second_items <- lapply(split_low, select_nth, n=2)
print(second_items)
``````
• Exercise: Create a list of vectors. In each vector try to have random values (numeric). Execute lapply in such a way that mean is calculated for every vector in list Waiting till 7:50
``````listA <- list(c(1,2,3,4,5,6,7),c(5,23,6,3,8,5,9,2,6),c(6,67,87,54,34,56))
lapply(listA, mean)
``````
• Write an anonymous function inside lapply to multiply the calculate the square of the mean
``````lapply(listA, function(x) { mean(x)^2})
``````

* lapply vs sapply

* Tricky unknown arguments

``````extreme_avg <- function(...){
y=list(...)
sum(...)
lapply(y, mean)

}

extreme_avg(c(1:100),c(200:300))

``````
• Refer Here for the changes done
• Useful functions
• abs()
• sum()
• mean()
• round()
• Combining two vectors is not equavalent to adding
``````vec1 <- c(1.5,2.5,8.4, 3.7, 6.3)
vec2 <- rev(vec1)

combined <- c(abs(vec1) , abs(vec2))

mean(combined)
``````
• Converting lists to vectors `unlist`
``````list1 <- list(16,9,14,5,3,18,13)

list2 <- list(17,8,6,2,13,16)

# convert list1 to vec1
vec1<- unlist(list1)
vec2 <- unlist(list2)

list3 <- list(c(17,8),c(6,2),c(13,16))
unlist(list3)

my_mean <- function(...) {
elements <- unlist(list(...))
mean(elements)
}

my_mean(c(1,2),c(3,4),c(5,6))
list4 <- list(c(17,8),c('6','2'),c('13','16'))
unlist(list4)
``````

This site uses Akismet to reduce spam. Learn how your comment data is processed.