Passing greek letters as colnames to kable - latex

I've been trying to name an R data frame columns with greek letters in order to call kable and get a latex output table with header names as these greek letters.
The result is that kable does not recognise column names as the way latex greek letters are written, or the arguments are not passing to the function in the correct format.
A <- t(as.data.frame(seq(1:4)))
colnames(A) <- c("$\\\\alpha$", "$\\\\beta$", "$\\\\delta$", "$\\\\gamma$")
A %>%
kable(.,"latex", escape = F, booktabs = T, linesep = "", align = "c")
Is there a way to do this propperly?
The best solution I,ve found so far is set column names of the data frame to NULL, and write the table headers form the knit options as follows:
A <- t(as.data.frame(seq(1:4)))
colnames(A) <- NULL
A %>%
kable(., "latex", escape = F, booktabs = T, linesep = "", align = "c") %>%
add_header_above(c("$\\\\alpha$", "$\\\\beta$", "$\\\\delta$", "$\\\\gamma$"))
But this way is quite messy and lacks of automation.
Finally I tried the following and it doesn't work too.
A <- t(as.data.frame(seq(1:4)))
A %>%
kable(., "latex", escape = F, booktabs = T, linesep = "", align = "c", col.names = c("$\alpha$", "$\beta$", "$\delta$", "$\gamma$"))
Thanks a lot.
PD: Here is the link to the issue on rmarkdown GitHub

Related

Let knitr/kable display latex code for further editing (.Rmd file)

Similar to a previous question, I have to convert the chunk of code I used to create a kableExtra table from a Rmarkdown file into pure LaTeX format in Overleaf. Unfortunately, I still have not understood how I can get the latex code by running the KableExtra table in the Rmd file.
The following is the YAML header:
---
[...]
output:
pdf_document: default
html_document:
---
the following is my code:
{r, results='asis', echo=FALSE}
res_kbl = kableExtra::kbl(merg, longtable=TRUE, booktabs = T, caption = "Table 1", digits = 2) %>%
kableExtra::kable_styling(latex_options = c("striped", "HOLD_position"), font_size = 10) %>%
kableExtra::add_header_above(c(" " = 1, "in Complete sample" = 2, "in Restricted sample" = 2, "MAJ" = 4, "MIN" = 4, "MAJ" = 4, "MIN" = 4)) %>%
kableExtra::add_header_above(c(" " = 1, "No. of funds" = 4, "Fund Size Complete sample (USD million nominal)" = 8, "Fund Size Restricted sample (USD million nominal)" = 8)) %>%
kableExtra::add_header_above(c(" " = 5, "Complete sample" = 8, "Restricted sample" = 8)) %>%
kableExtra::row_spec(row = nrow(merg) - 1, underline = T, extra_css = "border-bottom: 2px solid;")
My question: How can I get the Latex code for the res_kbl table I have created?
Any suggestion would be very much appreciated!
If I understand right, you want to get the LaTex code of the kable res_tbl.
In this case,
Specify format = "latex" in kableExtra::kbl() (or knit::kable())
Next, writeLines(res_kbl)
Instead, you don't need to assign res_kbl variable.
You can use additional pipe operator with writeLines().
The result of writeLines(res_kbl) will give the code you want. But the code can be complex because kableExtra package has so many functionalities.
In addition when using only writeLines(), you don't need asis part in the chunk option. However, comment option can be a problem if you want to use it in the final document not in the console. Set the comment as blank text in that chunk.

Split a table and send the Hex key

I am tryin to convert a table I have with a limit of 16 characters to hex keys and then store those hex keys in another table in the same order as the original string.
I have found a function using some online help which can take a string, split it into each character and assign that character to a space in a table.
So if I write function("Hello World!")
the return of the function would be table= {H, e, l, l, o, , W, o, r, l, d, !)
Now I need to limit this to only accept 16 characters and any more than that are discarded.
The function goes as
local str = "Hello World"
local chars = {}
for c in string.gmatch(str, ".") do
chars[#chars+1] = c
end
How can I limit this to 16 elements in the table?
My second question would be after I create this table, how do I go about changing each element of this table to a hex key and storing it in another table in the same order as the original string?
EDIT1: Thank you luke10000 for suggesting the if char.. method, it works perfectly. Now the next part is to convert this to hex and place it in a table.
I found a function which does this operation but there was no explanation with it at all, I understand some of it but not all. I can only print with this to the console all the hex keys.
function hex_dump(buf)
for byte=1, #buf, 16 do
local chunk = buf:sub(byte, byte+15)
--io.write(string.format('%08X ',byte-1)) -- 0's
chunk:gsub('.', function (c) io.write(string.format('0x%X ',string.byte(c))) end)
io.write(string.rep(' ',3*(16-#chunk)),"\n")
--io.write(' ',chunk:gsub('%c','.'),"\n") -- add the character infront of hex key
end end
for _, chars in ipairs(chars) do
hex_dump(chars) end
I'm not sure how the rest of your post is related to your actual problem.
I am tryin to convert a table I have with a limit of 16 characters to
hex keys and then store those hex keys in another table in the same
order as the original string.
I'm also not sure what you mean with "hex key".
local input = {"H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"}
local output = {}
for i,v in ipairs(input) do
output[i] = string.format("0x%X", v:byte())
if i == 16 then break end
end
print(table.concat(output, ", "))
Regarding your other questions:
local str = "Hello World"
local chars = {}
for c in string.gmatch(str, ".") do
chars[#chars+1] = c
end
How can I limit this to 16 elements in the table?
Simply limit your input string to 16 characters.
for c in str:sub(1,16):gmatch(".") do ...
My second question would be after I create this table, how do I go
about changing each element of this table to a hex key and storing it
in another table in the same order as the original string?
If your actual problem is to get a table of number representations from a string, simply use string.byte
local str = "Hello world! This is a wonderful day.!"
local output = table.pack(str:byte(1, 16))

R-Leaflet Map - Help me to Combine 2 legends in R leaflet

I making an R Leaflet Map and I have 2 legend. how to combine them?
thanks
Understanding the structure of your map (str(mapObject))object in R can be a helpful starting point. This can be useful for making "aftermarket" edits to legends.
I tried this as a solution to your problem:
# Concatenate the vectors that define each set of colors and their corresponding values:
require(spData)
require(leaflet)
require(sf)
# loading shapes of countries from the package spData
data(world)
world <- st_read(system.file("shapes/world.gpkg", package="spData"))
africa <- world[world$continent == "Africa",]
asia <- world[world$continent == "Asia", ]
asiaPal <- colorNumeric("Reds", domain = asia$pop)
africaPal <- colorNumeric("Blues", domain = africa$pop)
map <- leaflet() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addPolygons(data = asia,
color = ~asiaPal(asia$pop)) %>%
addPolygons(data = africa,
color = ~africaPal(africa$pop)) %>%
addLegend("bottomright", pal = asiaPal, values = asia$pop, title = "Asian Population") %>%
addLegend("bottomright", pal = africaPal, values = africa$pop, title = "African Population")
# Colors
map$x$calls[[5]]$args[[1]]$colors <-
c(map$x$calls[[5]]$args[[1]]$colors, map$x$calls[[4]]$args[[1]]$colors)
# Labels
map$x$calls[[5]]$args[[1]]$labels <-
c(map$x$calls[[5]]$args[[1]]$labels, map$x$calls[[4]]$args[[1]]$labels)
# Get rid of Old Legend:
map$x$calls[[4]] <- NULL
where your legends result from elements 4 & 5 of map$x$calls.
This doesnt work very nicely. I suspect it's because these list elements are not the end result, and the elements of the map object are provided to javascript/html when rendering the map. That said, I dont know if it's easily possible to do what you are trying to achieve, without poking around in the actual HTML that results.

Split string into list of words and separators

Given this string:
one#two*three#four#five*
What is a fast solution to extract the list of Pairs?
Each pair contains the word with its separator character like this:
[
['one', '#'],
['two', '*'],
['three', '#'],
['four', '#'],
['five', '*']
]
Specifically in my case I want to use both white space and new line characters as separators.
You'd need a regular expression:
(\w+)([#|*])
See example Dart code here that should get you going: https://dartpad.dartlang.org/ae3897b2221a94b5a4c9e6929bebcfce
Full disclosure: dart is a relatively new language to me.
That said, regex might be your best bet. Assuming you are only working with lowercase a-z letters followed by a single character, this should do the trick.
RegExp r = RegExp("([a-z]+)(.)");
var matches = r.allMatches("one#two*three#four#five*");
List<dynamic> l = [];
matches.toList().asMap().forEach((i, m) => l.add([m.group(1), m.group(2)]));
print(l);
Based on other responses here's my solution for white spaces and new lines as separators:
void main() {
RegExp r = RegExp(r"(\S+)([\s]+|$)");
var text = 'one two three \n\n four ';
var matches = r.allMatches(text);
List<dynamic> l = [];
matches.toList().asMap().forEach((i, m) => l.add([m.group(1), m.group(2)]));
print(l);
}
Output
[[one, ], [two, ], [three,
], [four, ]]
Explanation: https://regex101.com/r/cRpMVq/2

Citing within an RMarkdown table

I am attempting to create a table which has citations built into the table. Here is a visual of what I am trying to achieve.
As far as I know you can only add footnotes in rowvars or colvars in kableExtra (love that package).
# Create a dataframe called df
Component <- c('N2','P3')
Latency <- c('150 to 200ms', '625 to 800ms')
Location <- c('FCz, Fz, Cz', 'Pz, Oz')
df <- data.frame(Component, Latency, Location)
Below is my attempt after reading through kableExtra's Git page
# Trying some code taken from the kableExtra guide
row.names(df) <- df$Component
df[1] <- NULL
dt_footnote <- df
names(dt_footnote)[1] <- paste0(names(dt_footnote)[2],
footnote_marker_symbol(1))
row.names(dt_footnote)[2] <- paste0(row.names(dt_footnote)[2],
footnote_marker_alphabet(1))
kable(dt_footnote, align = "c",
# Remember this escape = F
escape = F, "latex", longtable = T, booktabs = T, caption = "My Table Name") %>%
kable_styling(full_width = F) %>%
footnote(alphabet = "Jones, 2013",
symbol = "Footnote Symbol 1; ",
footnote_as_chunk = T)
But this code only works on the headers. The ultimate goal would be if I could use a BibTex reference such as #JonesFunctionalMixedEffectModels2013 such that the final part of the code would look like
footnote(alphabet = #davidsonFunctionalMixedEffectModels2009,
symbol = "Footnote Symbol 1; ", footnote_as_chunk = T)
Anyone have any ideas?
Thanks
What I did at the end was to generate a temporary table with pander, then copy the references' number manually to my kable
pander(
df,
caption = "Temporal",
style = "simple",
justify = "left")

Resources