以编程方式将数据帧转换为命名列表

问题描述 投票:0回答:1

我正在尝试使用 R 中的 Reactable 库中的格式化选项。我想以编程方式从映射数据帧创建格式化。

Reactable 期望格式声明为

reactable(iris[1:5, ], columns = list(
  Sepal.Length = colDef(name = "Sepal Length"),
  Sepal.Width = colDef(name = "Sepal Width"),
  Species = colDef(align = "center")
))

但是我已经有一个将实际列映射到显示列的数据框。

有没有办法将映射数据框列转换为命名列表。映射数据框将有 2 列,原始列和显示列

我想进一步扩展它,添加更多的附加功能。进一步的列格式如下所示,

percent = colDef(format = colFormat(percent = TRUE, digits = 1)). 

我可以简单地向我的数据框添加更多列。

我尝试使用字符串连接转换为这种格式,但这不起作用。

我拥有的带有虹膜数据的示例代码是,

df <- iris
colnames(df) <- c('sep_l', 'sep_w','pet_l','pet_w','spec')
df$per <- df$sep_w/df$sep_l

col2 <- c('sep-l', 'sep-w', 'pet-l','pet-w', 'species', 'pct')

df_mapping <- cbind(colnames(df) , col2) %>% as.data.frame()
colnames(df_mapping) <- c('og','new')

df_mapping %<>%
 mutate(
  fmt = paste0(og, ' = colDef(format = colFormat(percent = TRUE, digits = 1))')
 )

reactable(df, columns = list(df_mapping$fmt))
r shiny reactable
1个回答
0
投票

这里是使用

eval
parse
的解决方案,因为看起来您想使用文本块运行表达式

library(reactable)
library(dplyr)
library(magrittr)

#get sample df
df <- iris
colnames(df) <- c('sep_l', 'sep_w','pet_l','pet_w','spec')
df$per <- df$sep_w/df$sep_l

col2 <- c('sep-l', 'sep-w', 'pet-l','pet-w', 'species', 'pct')

df_mapping <- cbind(colnames(df) , col2) %>% as.data.frame()
colnames(df_mapping) <- c('og','new')


# add character strings that will be used for the list command below (you forgot name== in your example)
df_mapping %<>%
  mutate(
    fmt = paste0(og,"= colDef(name='",paste(og),"'",",format = colFormat(percent = TRUE, digits = 1))"))



# paste the code together
text=paste0("list(",paste(df_mapping$fmt,collapse=","),")")

# use parse (returns the parsed, but unevaluated expression) and eval (will evaluate the parsed expression)
reactable(df, columns = eval(parse(text=text)))
© www.soinside.com 2019 - 2024. All rights reserved.