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.
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)
CodePudding user response:
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)
CodePudding user response:
If your sole question is how to name the first column, you can just create a new column with mutate
using the row names and then remove the original row names like so:
library(tidyverse)
library(rhandsontable)
DF %>%
mutate(order = rownames(DF)) %>%
as_tibble() %>%
select(order, everything())
Which gets you this:
# A tibble: 5 × 4
order integer numeric factor_allow
<chr> <int> <dbl> <ord>
1 One 1 0.492 a
2 Two 2 0.102 b
3 Three 3 0.522 c
4 Four 4 0.474 d
5 Five 5 -0.633 e
And if you wanna save it and make it into the rhandsontable
:
DF <- DF %>%
mutate(order = rownames(DF)) %>%
as_tibble() %>%
select(order, everything())
rhandsontable(DF,rowHeaderWidth = 96) %>%
hot_col("factor_allow", allowInvalid = TRUE)