7
How is it possible, in the R
, apply several functions to the same object?
Example:
Let’s say I have a vector x
.
set.seed(123)
x <- rnorm(10)
x
# [1] -0.56047565 -0.23017749 1.55870831 0.07050839 0.12928774
# [6] 1.71506499 0.46091621 -1.26506123 -0.68685285 -0.44566197
And I need to apply a series of functions on this vector. Let’s say, just for example that these functions were: mean, standard deviation, minimum and maximum.
The most naive way to do this is to call each function separately.
mean(x)
# [1] 0.07462564
sd(x)
# [1] 0.9537841
max(x)
# [1] 1.715065
min(x)
# [1] -1.265061
How could I abstract these four called by just one who was more flexible?
Editing
The idea is that the applied functions can be defined on time, excluding the function min()
or adding the function median()
, for example, as needed at the time.
A map
applies a function to several values. Doubt here is how to do otherwise, how to apply multiple functions to a value.
Why did you ask the question if you already knew the answer?
– JdeMello
Why other people may have doubt. So we are producing material on
R
in Portuguese for future readers– Tomás Barcellos
I understand, but then it’s important that you explain that in your question and give your answer within the question.
– JdeMello
I wouldn’t have responded if someone had introduced the purrr. I know the community has people who know the package better than I do and could have answered the question
– Tomás Barcellos
Moreover, this answer only complements the others with another approach
– Tomás Barcellos
Still, you could have given your answer and explained in the question how you can improve it.
– JdeMello
@Jdemello Recommended Reading: Meta Discussion on Answer your own question
– Bacco