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

时间:2020-04-12 07:18:53

标签: r shiny

我正在尝试使用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")
))

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

有没有一种方法可以将映射数据框列转换为命名列表。映射数据框将分为两列,即原始列和显示列

我想进一步扩展它,添加更多的附件。就像进一步的列格式一样,

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))

1 个答案:

答案 0 :(得分:0)

这是使用evalparse的解决方案,因为您似乎想使用文本块来运行表达式

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)))