blue-sky
blue-sky

Reputation: 53806

lapply , sapply, and apply function in simple context

Running this code in R :

pr <- function(x) {
  x
}

lapply(c("a" , "b") , pr)

sapply(c("a" , "b") , pr)

apply(c("a" , "b") , pr)

returns :

> pr <- function(x) {
+   x
+ }
> 
> lapply(c("a" , "b") , pr)
[[1]]
[1] "a"

[[2]]
[1] "b"

> 
> sapply(c("a" , "b") , pr)
  a   b 
"a" "b" 
> 
> apply(c("a" , "b") , pr)
Error in match.fun(FUN) : argument "FUN" is missing, with no default

Here is my understanding of returns values of lapply , sapply , apply in above context:

lapply returns a list , is this signified by [[1]]?

sapply returns a vector but why are vector dimensions [1] not returned in response?

apply returns an error , why is this occurring?

Upvotes: 1

Views: 1861

Answers (1)

akrun
akrun

Reputation: 886948

The lapply/sapply loops through each element i.e. in this case each element of the vector (c('a', 'b')). If it is a data.frame, the columns will be the looped and a matrix is a vector with dimensions, therefore, each element will be looped and the function is applied. The output returned is a list for lapply and sapply here it is a vector, but it depends on the argument simplify. By default it is simplify = TRUE, so if the lengths of the output elements are same, it returns a vector.

With apply, we needs a MARGIN argument. The MARGINs are there for data.frame or matrix. Suppose, if we convert the vector to a matrix, then with MARGIN it works

apply(t(c("a" , "b")) , 2, pr)

If it is a single column matrix, use the MARGIN=1

apply(matrix(c('a', 'b')), 1, pr)

It could return a list, vector etc depending on the length of the output element. Here, it is just returning the values. So, it is a vector

Upvotes: 3

Related Questions