lanselibai
lanselibai

Reputation: 1273

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

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?

Upvotes: 3

Views: 58

Answers (3)

Rich Scriven
Rich Scriven

Reputation: 99361

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)))

Upvotes: 3

DJack
DJack

Reputation: 4940

What about this :

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

color.gradient.3(10)

or

color.gradient.3 <- function(n){
  RdWh <- colorRampPalette(c("red", "white"))
  GrWh <- colorRampPalette(c("green", "white"))
  BlWh <- colorRampPalette(c("blue", "white"))
  c(RdWh(n/3), GrWh(n/3), BlWh(n/3))
}

color.gradient.3(30)

Upvotes: 1

Andrew Gustar
Andrew Gustar

Reputation: 18425

You could do this...

cg3 <- function(n) sapply(color.gradient.3, function(x) x(n))

cg3(10)
      [,1]      [,2]      [,3]     
 [1,] "#FF0000" "#00FF00" "#0000FF"
 [2,] "#FF1C1C" "#1CFF1C" "#1C1CFF"
 [3,] "#FF3838" "#38FF38" "#3838FF"
 [4,] "#FF5555" "#55FF55" "#5555FF"
 [5,] "#FF7171" "#71FF71" "#7171FF"
 [6,] "#FF8D8D" "#8DFF8D" "#8D8DFF"
 [7,] "#FFAAAA" "#AAFFAA" "#AAAAFF"
 [8,] "#FFC6C6" "#C6FFC6" "#C6C6FF"
 [9,] "#FFE2E2" "#E2FFE2" "#E2E2FF"
[10,] "#FFFFFF" "#FFFFFF" "#FFFFFF"

Upvotes: 0

Related Questions