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

时间:2018-11-20 03:54:11

标签: 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

如何从

这样的字符串中添加所有新的标题名称
(names2<-c('SL','SW','PL','PW','SPECIES'))
[1] "SL"      "SW"      "PL"      "PW"      "SPECIES"

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

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

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

2 个答案:

答案 0 :(得分:3)

set_header_df用于标题值的较小修改。如果要将df列名与一组一个或多个新的标题行进行映射,可以使用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 https://davidgohel.github.io/flextable/articles/layout.html#define-headers-with-a-reference-table

PayPalPayment payment = new PayPalPayment(new BigDecimal(amount), "USD", "Football Payment", PayPalPayment.PAYMENT_INTENT_SALE);
//Creating Paypal Payment activity intent
Intent intent = new Intent(activity, PaymentActivity.class);
//putting the paypal configuration to the intent
intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

//Puting paypal payment to the intent
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);

//Starting the intent activity for result
//the request code will be used on the metho
//onActivityResult
startActivityForResult(intent, Url.PAYPAL_REQUEST_CODE);

enter image description here

答案 1 :(得分:1)

好的,经过几次编辑后,我希望它对您有用。

您的方法似乎也很好。

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

ft <- flextable( head( iris ),
                   col_keys = names1 )

oldHeaders <- names1
newHeaders <- names2

headerlist <- setNames(as.list(newHeaders), 
                       oldHeaders)

ft <- do.call(set_header_labels, c(list(x = ft, top = F), headerlist))
ft