Village.Idyot
Village.Idyot

Reputation: 2073

How to add header to row header column in R dataframe?

In running the below simple code, I would like to add a column header to the far-left row header column of the table as show in the below image. How would this be done? If this makes a difference, the code is run inside the package Shiny but for the sake of brevity in the code below I took the core code out of Shiny.

enter image description here

I can change row 2, column 1, of the DF dataframe from a value of "2" to "22" with this command: DF[2,1] <- 22; but running DF[0,0] <- c("Header") gives "Error in x[[jj]] : attempt to select less than one element in get1index ".

Code:

library(rhandsontable)

DF = data.frame(
  integer = 1:5,
  numeric = rnorm(5),
  factor_allow = factor(letters[1:5], 
                        levels = letters[5:1],
                        ordered = TRUE
  ),
  stringsAsFactors = FALSE)

rownames(DF) <- c("One","Two","Three","Four","Five")

rhandsontable(DF,rowHeaderWidth = 96) %>%
  hot_col("factor_allow", allowInvalid = TRUE)

Upvotes: 1

Views: 2475

Answers (1)

ViviG
ViviG

Reputation: 1726

As mentioned in the comments, it is not possible to add header to DF[0,0]. One workaround is to replace rowHeaders with a column instead using dplyr:

library(rhandsontable)
library(dplyr)

# Renders the same colour as in the rowHeader
color_renderer <- "
  function(instance, td) {
    Handsontable.renderers.TextRenderer.apply(this, arguments);
    td.style.background = '#F0F0F0';
  }
"

DF = data.frame(
  integer = 1:5,
  numeric = rnorm(5),
  factor_allow = factor(letters[1:5],
                        levels = letters[5:1],
                        ordered = TRUE),
  stringsAsFactors = FALSE
)

# Create your Header column    
DF = DF %>%
  mutate(Header = c("One", "Two", "Three", "Four", "Five"),
         .before = 1)

# remove rowHeaders from your table, add colour to first column
rhandsontable(DF, rowHeaderWidth = 96, rowHeaders = NULL) %>%
  hot_col("factor_allow", allowInvalid = TRUE) %>%
  hot_col("Header",renderer = color_renderer)

enter image description here

Upvotes: 1

Related Questions