Explain with an example how to perform lapply() function using R.

To apply lapply() to a function, we have to define a vector

# vector

v <- c(1,2,3,4,5)

Here v is a vector consisting of numbers ranging from 1 to 5.Now let us build a custom function to see how lapply() works.

# our custom function

addrand <- function(x){

    # Get a random number

    ran <-sample(x=1:10,1)

    # return x plus the random number

    return(x+ran)

}

# lapply()

lapply(v,addrand)

This will give the following output

  1. 7
  2. 11
  3. 9
  4. 5
  5. 6



Your Answer

Interviews

Parent Categories