Reputation: 28754
I have a vector like (1,100,2,30,20,...)
And what I'd like to do is mapping these value to another value. Actually I can do a loop on these values, but I wonder whether I can make the map function vectorized. For example, I'd like to map the value to its bucket such as following
1 -> "< 10",
20 -> "10 to 50",
60 -> "50 to 100",
Thanks
Upvotes: 4
Views: 9896
Reputation: 323
Use Purrr's map
(https://www.rdocumentation.org/packages/purrr/versions/0.1.0/topics/map )
e.g.
xx=c(1,4,0,3,1)
f = function(s) return(c((10*s):(10*s+9)))
xx %>% map(f)
Upvotes: 2
Reputation: 93813
What about something like this?
test <- c(1,24,2,30,20)
sapply(
# bin the data up
findInterval(test,seq(0,30,10)),
# apply a particular function to the data element
# dependent on which bin it was put into
function(x) switch(x,sqrt(x),sin(x),cos(x),tan(x))
)
[1] 1.0000000 -0.9899925 1.0000000 1.1578213 -0.9899925
Upvotes: 4