Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the list created below. Write a short script using lapply() to test whi

ID: 3301578 • Letter: C

Question

Consider the list created below. Write a short script using lapply() to test which elements in the list are functions. Then return only those list elements which are functions and assign this result to variable listSub. Make sure that the function you create will work with arbitrary lists. It is not acceptable to just gure out yourself which elements contain functions and subset bigList below. Make it automated and exible.

bigList <- list(x = 1:8, y = data.frame(norm = rnorm(5, 0, 1)), z = function(x) {x}, t1 = function(x, y) {x + y ^ exp(x)}, char = "This is a character", t2 = function(lambda) {lambda ^ (1 / pi)})

Explanation / Answer

The following R program gives the desired result.

> bigList <- list(
+   x = 1:8,
+   y = data.frame(norm = rnorm(5, 0, 1)),
+   z = function(x) {x},
+   t1 = function(x, y) {x + y ^ exp(x)},
+   char = "This is a character",
+   t2 = function(lambda) {lambda ^ (1 / pi)}
+   )
> find_funcs <- function(testList){
+   listSub <- which(lapply(bigList,class)=="function")
+   return(names(listSub))
+ }
> find_funcs(bigList)
[1] "z" "t1" "t2"