如何为R语言dataframe的行标题列添加表头?
问题:为rhandsontable的行标题列添加表头
我在用rhandsontable(配合Shiny使用,以下是核心代码)时,想给表格最左侧的行标题列加一个表头。我知道可以用DF[2,1] <- 22修改数据框的单元格值,但尝试DF[0,0] <- c("Header")时会报错:Error in x[[jj]] : attempt to select less than one element in get1index。
原代码:
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)
解决方法
rhandsontable原生没有直接给行标题列加表头的选项,不过有两种简单方法可以实现需求:
方法一:将行名转为普通列(推荐)
把原行名提取为数据框的第一列,给这列设置表头,完美模拟行标题列带表头的效果,还能自定义样式:
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) # 把行名转为第一列,设置表头为你想要的名称 DF <- cbind(行标题 = rownames(DF), DF) rownames(DF) <- NULL # 移除原行名,避免重复显示 rhandsontable(DF, rowHeaderWidth = 0) %>% # 关闭原生行标题列 hot_col("行标题", readOnly = TRUE, width = 96) %>% # 把自定义列设为只读,宽度和原行标题一致 hot_col("factor_allow", allowInvalid = TRUE)
方法二:用CSS添加表头(无需修改数据)
如果不想改动数据结构,可以通过自定义CSS在原生行标题列上方添加表头文本,在Shiny的UI部分加入以下样式即可:
# 在Shiny的UI函数里添加 tags$head( tags$style(HTML(" /* 给行标题列添加表头 */ .ht_clone_left .ht_master table thead tr th:first-child::before { content: '行标题'; display: block; text-align: center; padding: 8px; font-weight: bold; border-bottom: 1px solid #ccc; } ")) )
添加后直接运行你原来的代码,就能看到行标题列上方出现表头。
内容的提问来源于stack exchange,提问作者Village.Idyot
相关产品推荐
相关产品推荐

