Accenture Interview Questions | What is lapply and sapply?

Question

Apply functions

in progress 0
TheDataMonk 4 years 3 Answers 844 views Grand Master 0

Answers ( 3 )

  1. lapply() takes a list and a function as input and returns a list of the same length ,
    each element of which is the result of applying a function to the corresponding element of X.

    Example:
    l1 = c(‘shikhar,rohit,virat’)
    l1
    #output
    “shikhar,rohit,virat”
    l2 = lapply(l1,toupper)
    l2

    sapply() function takes list, vector or data frame as input and gives output in vector or matrix.
    sapply() function does the same job as lapply() function but returns a vector.

    > l3 = sapply(l1,toupper)
    > l3
    shikhar,rohit,virat
    “SHIKHAR,ROHIT,VIRAT”
    > typeof(l2)
    [1] “list”
    > typeof(l3)
    [1] “character”
    #output
    “SHIKHAR,ROHIT,VIRAT”

  2. lapply():

    l in lapply() stands for list. The difference between lapply() and apply() lies between the output return. The output of lapply() is a list. lapply function takes list, vector or Data frame as input and returns only list as output.

    Sapply()

    sapply function takes list, vector or Data frame as input. It is similar to lapply function but returns only vector as output.sapply() function does the same jobs as lapply() function but returns a vector.

  3. Both sapply() and lapply() functions takes list, vector or data frame as input. The major DIFFERENCE between both of them is lapply() returns a list (l in lapply() stands for list) whereas sapply() returns a vector.

Leave an answer

Browse
Browse