从flextable中的字符串动态设置colnames

J.C*_*Con 6 r flextable officer

flextable帮助的细节描述了将新的标头,对每一个新的头名手动键入每个现有的头名,如下所示:

library(flextable)
ft_1 <- regulartable(head(iris))
ft_1 <- set_header_labels(ft_1, Sepal.Length = "SL",
                          Sepal.Width = "SW", Petal.Length = "PL",
                          Petal.Width = "PW"
)
ft_1
Run Code Online (Sandbox Code Playgroud)

我怎样才能从一个字符串中添加所有新的标题名称,例如

(names2<-c('SL','SW','PL','PW','SPECIES'))
[1] "SL"      "SW"      "PL"      "PW"      "SPECIES"
Run Code Online (Sandbox Code Playgroud)

?

到目前为止,我已经管理了一个非常hacky的解决方案:

names(names2)<-names(ft_1$header$dataset[1,])

ft_1$header$dataset[1,]<-names2
Run Code Online (Sandbox Code Playgroud)

Dav*_*hel 5

set_header_labels用于标题值的微小修改。set_header_df如果要将 df 列名称与一组一个或多个新标题行进行映射,可以使用:https : //davidgohel.github.io/flextable/articles/layout.html#define-headers-with-a-reference-桌子

library(flextable)

names1 <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species")
names2 <- c('SL','SW','PL','PW','SPECIES')

ft <- flextable( head( iris ) )
ft <- set_header_df(x = ft, mapping = data.frame(keys = names1, values = names2, stringsAsFactors = FALSE),
              key = "keys" )

# the following call is needed as header formats have been 
# replaced by vanilla formats when set_header_df() has been called
ft <- theme_booktabs(ft) 
ft
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明