I am trying to set up a table with colored tiles that are colored conditionally based on the average of each column. Basically, the tile would be red if the value is below the average, and green if above the average. I used a simple if else statement in my function below.
I will eventually use the "formattable" package and color_tile function within the package.
I have attempted to write my own function to pick the colors, but it is only successfully labelling the first row in my data frame.
#library(formattable) # not used in this example
green <- "#71CA97"
red <- "#ff7f7f"
col1 <- c(1.2, 4.2, 5.6, 7.1)
col2 <- c(5.0, 1.3, 10.3, 6.0)
col3 <- c(4.7, 6.3, 1.5, 6.3)
mydata <- data.frame(col1, col2, col3)
colorPicker <- function(x) {
if(x <= 5) {return("red")}
else {return("green")}
}
tile.colors <- lapply(c(mydata), colorPicker)
Warning message: In if (x <= 5) { : the condition has length > 1 and only the first element will be used
"tile.colors" returns the correct colors, but only for the first row.
I would eventually call "tile.colors" in the formattable function, but for now I am just trying to get the color picking function correct.
Is there a more efficient way to accomplish this task?