I have a flextable() where I want to make the header have two font sizes. One size for the main text (say, 20 pt font), and a smaller for the parenthetical text (12 pt font). Here's code that makes the entire header 20 pt.
Note: In the final solution, I'd prefer not to make the parenthetical text an entirely new row unless it can be as near to the original text as the below example shows.
library(flextable)
library(dplyr)
set_flextable_defaults(font.size = 20) #Works but makes all header size 20
flextable(test) %>%
set_header_labels(values = list(name = "Name", med_score = "Score (Median)", mean_score = "Score (Mean)")) %>%
align(align = "center", part = "header")
EDIT: Pictures added
Here's what it looks like currently:
And here's what I want it to look like:
Note: I made this goal table in PowerPoint. It looks different in many ways from the original one because I haven't formatted the original. The only difference that I'm trying to replicate is having (median) and (mean) being smaller than Score as well as them being in the same header cell.
You could use compose, as_paragraph and as_chunk to achieve it.
For reference: https://ardata-fr.github.io/flextable-book/cell-content-1.html#multi-content
library(flextable)
ft <- flextable(airquality[ sample.int(10),])
compose(
ft,
j = "Ozone",
part = "header",
value = as_paragraph(
"Ozone ",
as_chunk(
" (Median)",
props = fp_text_default(color = "#006699", font.size = 5)
)
)
)
Related
I have set of images. For each image I need to exract the intensity of so-called "web safe colors"
As an output I need a dataframe, where each row is am image, and each column is a color.
Here is how I get safe colors
library(rvest)
library(dplyr)
colors = read_html("https://en.wikipedia.org/wiki/Web_colors#Color_table") %>%
html_nodes("h3+ .wikitable td") %>%
html_text() %>%
trimws()
Here is an example of image:
library(magick)
im = image_read("https://farm4.staticflickr.com/3579/3370591414_f321bd33ff_z.jpg")
I can transform it to different number of color like this:
im %>%
image_quantize(max=12)
But since I need to compare images, I want each image to be presented in the same palette (and I've chose web safe palette).
So, finally I end up with this. Not exactly the same that I wanted, but works.
# recolor image
image_id = im
num_vector = as.numeric(img_vector)*255
num_vector = round(num_vector / int) * int
#loop for pixels
for(i in 1:90){
for(j in 1:120){
pixel = num_vector[i,j,]
whichcolor = which(tmp$rgb == paste0(pixel, collapse = "|"))
color = tmp$color_id[whichcolor]
result = rbind(result, data.frame(image_id, i, j, color))
}
}
I'm looking for a workaround solution for a known issue where \cellcolor from the colortbl package does not work properly with \makecell. As mentioned, there probably already exists a workaround in Latex, but I'm hoping for a solution in terms of the R package kableExtra when producing pdfs using rmarkdown. Here's a screenshot; as can be seen, some cells are not filled entirely.
Here's a minimally reproducible example in rmarkdown:
library(kableExtra)
library(tidyverse)
# Data --------------------------------------------------------------------
df <- tribble(
~col1, ~col2,
"really long text that needs to be broken into multiple lines so it can fit", 4,
"really long text that needs to be broken", 4,
"really long text that needs a fix", 4,
) %>%
modify_at(
.x = .,
.at = 1,
.f = stringr::str_wrap,
width = 25
)
# Table -------------------------------------------------------------------
df %>%
mutate(across(.cols = 1, .fns = linebreak, align = "l")) %>%
kbl(x = ., escape = FALSE) %>%
row_spec(row = 1:3, background = "#e5e5e5")
One possible fix is to specify keep_tex: true in the YAML and fix the issue in the .tex file manually before using pandoc. But I'm generating many tables and this can't possibly be efficient. Any suggestion of a potential workaround would be greatly appreciated.
Why not use column_spec to force the line wrap rather than using makecell and linewrap?...
library(tibble)
library(dplyr) #for the pipe
library(kableExtra)
df <- tribble(
~col1, ~col2,
"really long text that needs to be broken into multiple lines so it can fit", 4,
"really long text that needs to be broken", 4,
"really long text that needs a fix", 4,
)
kbl(df) %>%
column_spec(1, width = "30mm") %>%
row_spec(row = 1:3, background = "#e5e5e5")
Another solution that worked for my use case (where column_spec(width) fails), is based on leandriis's comment in this post. Specifically, we wrap the \colorbox command around the \makecell command to have a completely colored cell. For example \colorbox[HTML]{hexcode}{\makecell{text}}. This requires that we create our own custom linebreak function, which not only wraps our text in \makecell but also wraps that latex code in a \colorbox.
# Custom linebreak --------------------------------------------------------
linebreak_custom <- function(x, align = "l", linebreaker = "\n") {
ifelse(
# If '\n' is detected in a string, TRUE, or else FALSE
test = str_detect(x, linebreaker),
# For TRUE's, wrap text in \makecell and then in \colorbox
yes = paste0(
"\\cellcolor[HTML]{e5e5e5}{\\colorbox[HTML]{e5e5e5}{\\makecell[", align, "]{",
str_replace_all(x, linebreaker, "\\\\\\\\"), "}}}"
),
# Return as is if no '\n' detected
no = x
)
}
# Data --------------------------------------------------------------------
df <- tribble(
~col1, ~col2,
"really long text that needs to be broken into multiple lines so it can fit", 4,
"really long text that needs to be broken", 4,
"really long text that needs a fix", 4,
) %>%
modify_at(
.x = .,
.at = 1,
.f = stringr::str_wrap,
width = 25
)
# Table -------------------------------------------------------------------
df %>%
mutate(across(.cols = 1, .fns = linebreak_custom, align = "l")) %>%
kbl(x = ., escape = FALSE) %>%
row_spec(row = 1:3, background = "#e5e5e5")
This produces the desired output:
As noted, this solution may not be robust to future versions of kableExtra (as it involves, quite frankly, "hacking" the source code), and the solution suggested by Peter above should still be better in many use cases. I've created an issue via Github to bring this to their attention, so perhaps there could be an official fix in their code in the future.
I want to set the height of row constant or fixed for DT table output. for the table below you can see difference in height of rows.
so the scenario is when the number of character increases for eg second row in this case in first col then height should get adjust as same for all rows.
df <- data.frame(`quote` = c("the trader belongs to","trader have long ralationship withthe same market with my opinion on thaw its implemented mmnnhhh sdfghj fghj kjhgf tyui cvbnm",
"types of trads happens everytime when market slow","trades have leverage with",
"market is continious with the same platform trades"),
`share`= c(43,65,92,23,73),
`times` = c(86,98,55,12,08),
`parts`=c(4,7,4,8,3))
df<-datatable(df,
options = list(columnDefs =
list(list(className = 'dt-center',
targets = "_all"))),rownames = FALSE)
df
like in flextable i can do something like below but looking for fixed solution or any function for DT tables.
(ncols %in% c(4,5)) {
fl<-width(flxtable, width = d*0.3, j = 1)
fl<-width(flxtable, width = (d*0.7)/(ncols-1), j = 2:ncols)
d is left and right margin of docs template
I had success with this in the past:
DT::datatable(df) %>%
DT::formatStyle(names(df),lineHeight='80%')
Kudos to the post that helped me, however I fail to find it back now.
I am currently building an app and I want to have tooltips in a highcharter stock with additional information.
#Data
df <- data.frame(time = seq(as.Date("2021-03-10"), length = 10, by = "days"),
values = 1:10,
additionalInfo1 = LETTERS[1:10],
additionalInfo2 = letters[1:10])
#Packages
library(highcharter) #plots
library(xts) #conversion for stock-highchart
library(dplyr) #piping-operator
I know how to add additional information to a tooltip when using type="line". This can be done via
highchart_line <- hchart(df, "line", hcaes(x = time, y = values),
tooltip = list(headerFormat = "<b> Some Tooltipheader </b> <br/>",
pointFormat = paste0("index: {point.index} <br/>",
"time: {point.time} <br/>",
"additional1: {point.additionalInfo1} <br/>",
"additional2: {point.additionalInfo2}")))
and shows everything fine. The nice thing is that one can supply the whole data and hence has access to the columnnames.
When creating a type="stock", I need to convert the data to an xts while only using the times and the values:
stockdata_xts <- xts(x = df$values, order.by = df$time)
highchart_stock <- highchart(type="stock") %>%
hc_add_series(stockdata_xts, name = "someData",
tooltip = list(pointFormat = paste0(
"point.x: {point.x} <br/>",
"point.y: {point.y} <br/>",
"point.index: {point.index} <br/>"
))) %>%
hc_rangeSelector(enabled = FALSE)
Is there a way to put additional data for the tooltip in the stock-highchart such that the tooltip looks like the one in the linechart above? Maybe some functionality of the xts-object including more attributes for it which I don't know.
The reason why I want to use the stock-highchart is the navigator-bar. If there is a way to include the navigator-bar in the line-highchart, I would also be thankful. There is also a function highcharter::hc_navigator, but the documentation says that it is only applicable to highstocks. (see https://cloud.r-project.org/web/packages/highcharter/highcharter.pdf , page 50)
Yes, the navigator works in stockChart. For such tooltip customization, I think it will be best to use the dedicated formatter API function: https://api.highcharts.com/highstock/tooltip.formatter
Here you can find an article that can help you use JS code in R:
https://www.highcharts.com/blog/tutorials/working-with-highcharts-javascript-syntax-in-r/?fbclid=IwAR1Em2yNUsIJunTRS4IEbUwGksb5PC7LfZATLcyvb7uLS7ZvV7v4-e0L0
I would like to wrap and rotate column HEADER headings in a kable-latex table. I can control the width of the column using column spec, but I need to group columns in my table with a header, and it is the names in the header that I want to rotate and wrap. A very basic example of my table is below.
example <- data.frame(name="testname", score1=3, score2=2, score3=0)
table <- kable(example, format="latex", escape = F) %>%
column_spec(1:4, width = "5em") %>%
add_header_above(c(" " = 1, "Rhyme Product" = 2, "Sound ID Middle" = 1)) %>% add_header_above(c(" " = 1, "Exploring Words" = 2, "Early Skills" = 1), bold = T)
I would like to flip the first set of column groupings (Rhyme Product and Sound ID Middle) on their side (angle = -45) and wrap the text on two separate lines taking up a lot less space. Is this possible?
This one is a pretty simple fix. I'm surprised no one has answered it over the years. One possibility is that the setting did not exist when this question was answered.
To add the line breaks, add a \n to the column names where you would like the breaks to be. To rotate, add angle = "-45" to the add_header_above line you would like to modify. See the code below.
library(tidyverse)
library(kableExtra)
example <- data.frame(name="testname", score1=3, score2=2, score3=0)
table <- kable(example, format="latex", escape = F) %>%
column_spec(1:4, width = "5em") %>%
add_header_above(c(" " = 1, "Rhyme \nProduct" = 2, "Sound ID \nMiddle" = 1), angle = "-45") %>%
add_header_above(c(" " = 1, "Exploring Words" = 2, "Early Skills" = 1), bold = T)
table
Table output
Interestingly enough, the align argument accepts a vector of angles (i.e align = c("-45", "90")) to apply to each column. This is also true for row_spec. I have not seen anyone talking about this, nor is it anywhere in the documentation. It is really useful, however.