For my reactable table I want to create a function that compares 2 columns, namely one of this year and one of last year. I want the function to color the value in the current year column based on whether or not it's higher or lower than the value last year. So if the value is higher it should turn green, etc.
My function works for the most part but I can't get the function to access the index number of the value in the function.
This is what I have so far:
library(reactable)
reactable(test,
highlight = TRUE,
defaultPageSize = 20,
columns = list(
Maand = colDef(footer = "Totaal"),
year2020 = colDef(style = function(value) {
if (value > test[....index of value here...., "year2019"] ) {
color <- "#008000"
} else if (value >1) {
color <- "#e00000"
} else {
color <- "#777"
}
list(color = color, fontWeight = "bold")
})
),
defaultColDef = colDef(footer = function(values) {
if (!is.numeric(values)) return()
sum(values)
},
footerStyle = list(fontWeight = "bold")),
rowClass = "my-row"
)
It does work when I use a random index number like this:
reactable(test,
highlight = TRUE,
defaultPageSize = 20,
columns = list(
Maand = colDef(footer = "Totaal"),
year2020 = colDef(style = function(value) {
if (value > test[1, "year2019"] ) {
color <- "#008000"
} else if (value >1) {
color <- "#e00000"
} else {
color <- "#777"
}
list(color = color, fontWeight = "bold")
})
),
defaultColDef = colDef(footer = function(values) {
if (!is.numeric(values)) return()
sum(values)
},
footerStyle = list(fontWeight = "bold")),
rowClass = "my-row"
)
Can anyone tell me what I'm doing wrong? Thanks in advance!
I know this is rather late, but I was searching for a solution to a problem similar to yours. You need to provide an index to "loop" through the row. What you did previously "worked", because you compared each value to the first row in the year2019 column.
reactable(test,
highlight = TRUE,
defaultPageSize = 20,
columns = list(
Maand = colDef(footer = "Totaal"),
year2020 = colDef(style = function(value, index) {
if (value > test[index, "year2019"] ) {
color <- "#008000"
} else if (value >1) {
color <- "#e00000"
} else {
color <- "#777"
}
list(color = color, fontWeight = "bold")
})
),
defaultColDef = colDef(footer = function(values) {
if (!is.numeric(values)) return()
sum(values)
},
footerStyle = list(fontWeight = "bold")),
rowClass = "my-row"
)