Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign a same value as the argument to a vector of functions in R?

Tags:

r

apply

I have this code in R:

RdWh <- colorRampPalette(c("red", "white"))
GrWh <- colorRampPalette(c("green", "white"))
BlWh <- colorRampPalette(c("blue", "white"))
color.gradient.3 <- c(RdWh, GrWh, BlWh)

Then I want to get a vector

c(RdWh(10), GrWh(10), BlWh(10))

How to achieve this?

like image 486
lanselibai Avatar asked Jan 29 '26 09:01

lanselibai


1 Answers

To avoid writing a bunch of calls to colorRampPalette(), you could put your color vectors into a list, color, and run that list through sapply(), where we can also call n = 10 on each run at the same time. Then wrap with c() to get a vector result, as desired.

color <- list(RdWh = c("red", "white"), GrWh = c("green", "white"), BlWh = c("blue", "white"))
c(sapply(color, function(x) colorRampPalette(x)(10)))
like image 104
Rich Scriven Avatar answered Jan 30 '26 22:01

Rich Scriven



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!