Accenture Interview Questions | What is lapply and sapply?
Question
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
It will take less than 1 minute to register for lifetime. Bonus Tip - We don't send OTP to your email id Make Sure to use your own email id for free books and giveaways
Answers ( 3 )
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”
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.
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.