Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

Using index of value in function in R

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!

question from:https://stackoverflow.com/questions/65617449/using-index-of-value-in-function-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...