gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 23:10:30 28 4
gpt4 key购买 nike

flextable 帮助详细信息描述了如何添加新 header ,即根据每个新 header 名称手动键入每个现有 header 名称,如下所示:

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

如何从字符串中添加所有新的 header 名称,例如

(names2<-c('SL','SW','PL','PW','SPECIES'))
[1] "SL" "SW" "PL" "PW" "SPECIES"

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

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

ft_1$header$dataset[1,]<-names2

最佳答案

set_header_labels 用于对 header 值进行细微修改。如果您想将 df 列名称映射到一组一个或多个新标题行,则可以使用 set_header_df:https://davidgohel.github.io/flextable/articles/layout.html#define-headers-with-a-reference-table

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

enter image description here

关于r - 从flextable中的字符串动态设置colnames,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53385979/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com