+1 vote
2 views
in R Programming by (3.4k points)
edited by

I use the function apply whenever I want to do something “map”py in R

I want to know about the difference between them - how sapply, lapply, etc apply the function to be in input/grouped input, I just go through them until I get what I want as I don’t know what output will look like or what input will be.

So please can someone tell me when should I use which one and how?

Bonus question: Can plyr or reshape can be used to replace these entirely?

1 Answer

0 votes
by (46.1k points)
edited by

You can check the help file in R for the apply function, most of the functionality of apply family is covered by plyr package, but still some base functions are worth learning. I am giving examples of a few below:

  1. Apply: used to apply a function to the rows or columns of a matrix, not advised for data frames it coerce to a matrix first.

M <- matrix(seq(2,17), 55) apply(M,2,min) [23 4 5 6  apply(M,3, max) [25 9 13 17 

2.tapply: If function is applied to subsets of a vector, and subset is defined by some other vector which in most of the cases is  a factor.

A vector: x <- 1:21

factor (of the same length!) defining groups: y <- factor(rep(letters[2:6], each = 4))

Add up the values in a within each subgroup defined by b:

tapply(a,b,sum)q w e r t 11 27 43 59 75

For all others just check the help of R or comment down below.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...