Using the following extract from my Rmarkdown
for (swimmer in swimmers) {
cat('\\newpage')
cat('## ', swimmer, '\n\n')
dtEvents <- dtClub[name == swimmer, ][order(event)]
for (r in 1:nrow(dtEvents)) {
row <- dtEvents[r,]
title <- paste0('Event ', row$event, ' ', row$race_gender, ' ', row$age_group, ' ', row$distance, ' ', row$stroke)
dtRace <- dt[event == row$event & seed %between% c(row$seed-5, row$seed+5)][order(seed)]
cat(kbl(dtRace[, .(seed, name, age, club, seed_time_str, seed, heat, lane)],
align = c('r','l','c','l','r','r','r','r'), caption = title, longtable = FALSE) %>%
kable_styling(latex_options = c('striped','scale_down','repeat_header')))
cat('\n')
}
}
I'm ending up with the heading of the person's name printing underneath the tables on the first page rather than above them. I get a page break per person and all the data in tables, just the heading with their name is below all tables of data on their first page with remaining tables following on further pages.
Edit: On further inspection it appears the \newpage is not working at all. \pagebreak doesn't seem to work either.
I found that by using the information in this answer I was able to solve the problem. As a complete noob to kable/latex I wasn't aware of how tables are positioned within the document.
By adding kable_styling(latex_options = "HOLD_position") to the kable statement everything worked as required. There was also the odd part around making sure to use '\n' in the correct places when outputting latex statements in the R code else it gets a little upset.
Related
I am trying to create a table of terms in an rmarkdown pdf file. Basically, I would have the columns be the category of term on the left (using kable collapse_rows() feature), the quantity itself, then finally a description.
I am having trouble formatting my terms within the r code chunk for my kable- essentially, it is not reading them as LaTeX-styled terms. I have looked at previous questions and seen that I need to have the results = "asis" and use \\ instead of \ but still can't quite get it to work.
Here is my code chunk:
{r, results='asis'}
flux = c("$\\j_{FI}$","$\\j_{VG}$")
p_label = rep("flux", length(flux))
deets = c("Ingestion","Structural growth")
table = cbind(p_label,flux,deets)
kable(table,col.names = c("Quantity Type","Quantity","Description")) %>%
collapse_rows(columns = 1, latex_hline = "major", valign = "middle")
It produces this:
I'd like my terms to look like they do in the rest of the markdown document (when they are outside of code chunks)
Thanks!
I am using captioner (https://cran.r-project.org/web/packages/captioner/vignettes/using_captioner.html) to create table captions in Rmarkdown - the main reason is because I am using huxtable for conditional formatting and exporting to word. This is the only I have found to have numbered captions.
I was trying to reference the captions but the caption number is not in sequential order when citing the captions but only if the table_nums(..., display="cite") is before the tables. I was trying to give the range of table numbers and it changed the number of the last table. I The number isn't changed if the r table_nums('third_cars_table',display = "cite") is put after the captions. Is there a way to make sure that table numbers remain in sequential order? I'd also be happy with a better solution for numbered captions.
Reproducible example:
---
title: "Untitled"
output: bookdown::word_document2
---
```{r setup, include=FALSE}
library(captioner)
library(huxtable)
library(knitr)
library(pander)
table_nums <- captioner(prefix = "Table")
fig_nums <- captioner(prefix = "Figure")
knitr::opts_chunk$set(echo = TRUE)
```
## Description of tables
I am trying to put a description of tables
and say that these results are shown table numbers ranging
from the first table (`r table_nums('first_cars_table',display = "cite")`)
to the last table (`r table_nums('third_cars_table',display = "cite")`)
```{r, results='asis',echo=FALSE,eval.after=TRUE}
tablecap1=cat(table_nums(name="first_cars_table",caption='First car table'))
kable((cars[1:5,]))
tablecap2=cat(table_nums(name="second_cars_table",caption='second car table'))
kable(cars[6:10,])
tablecap3=cat(table_nums(name="third_cars_table",caption='third car table'))
kable(cars[10:15,])
```
The results:
A (terrible) workaround is to manually give the number ordering using display = FALSE. For example, inserting the following at the start of the document will ensure t1-t5 are sequentially numbered, no matter where the tables or first citations appear:
`r table_nums('t1', display = FALSE)`
`r table_nums('t2', display = FALSE)`
`r table_nums('t3', display = FALSE)`
`r table_nums('t4', display = FALSE)`
`r table_nums('t5', display = FALSE)`
I have not examined the captioner code but I expect that the document is read from top to bottom once and hence the numbering is stored in a first come, first served basis. Thus, I am not sure there are any other ways to get around this as it would involve some kind of pre-processing stage.
I have a word doc named a.doc formatted:
Name - Bob
Hair color - Red
Age - 28
...
I'd like to save the information after "Name - " "Hair color - " ... into a variable for access later in the script. Would the easiest way be to create a list:
Keywords = (Name, 'Hair color', Age)
Fileopen = open(a.doc)
Filecontent = readlines(fileopen)
For keywords in filecontent:
This is where I get stuck. I'm thinking I can add a statement allowing to grab after the " - " in each line.
EDIT:
To be more precise in my explanation of what I am looking to do:
I would like to grab the information in each line separately after the ' -
' and store it in a variable. For example Name - Bob will be stored in name equaling 'Bob'.
I have made some progress here since my previous update. I just know the way I am doing it does not allow for easily repeating.
I have successfully pulled the information utilizing:
filename = raw_input("choose your file: ")
print "you chose: %r" % filename
with open(filename) as fo:
for line in fo:
if "Name" in line: name = line.split(" - ", 1)[1]
print name
fo.close()
I know that I can continue to make a new 'if' statement for each of my strings I'd like to pull, but obviously that isn't the fastest way.
My REAL question:
How to make that if statement into a loop that will check for multiple strings and assign them to separate variables?
In the end I am really just looking to use these variables and reorder the way they are printed out which is why I need them separated. I attempted to use the 'keywords' but am not sure how to allow that to dynamically define each to a variable that I would like. Should I add them to a list or a tuple and subsequently call upon them in that manner? The variable name obviously has no meaning outside the program so if I called it from a tuple as in [0], that might work as well.
This code asks for the name, age, and hair color of the person, then returns the person's information while storing the information in the variable Filecontent and is stored until you close the shell:
def namesearch(Name, Hair, Age):
Keywords = ('Name - ' + Name + ', Hair Color - ' + Hair \
+ ', Age - ' + Age)
Fileopen = open('a.doc', 'r')
for line in Fileopen:
if Keywords in line:
global Filecontent
Filecontent = line
print line
Name = raw_input('Enter the person\'s name: ')
Hair = raw_input('Enter the person\'s hair color: ')
Age = raw_input('Enter the person\'s age: ')
namesearch(Name, Hair, Age)
This code returns the information in this format:
Name - (Name), Hair Color - (Hair Color), Age - (Age).
Note: This code can only search for names, not add them
I've built a Shiny dashboard app that shows a number of metrics data of scientific articles by university School. The app is at https://ttso.shinyapps.io/2amconf and the code https://gist.github.com/tts/900b4e27bf37e8969ebd with some sample data of file dataforcharts.csv which is the data source of my question here.
My problem is the NVD3 chart on the landing tab.
At first it draws OK the selected max 2 items (=articles) from the chosen School, which is All at the beginning. But whenever I select some School - and selectizeInput then updates the list of items of that School - nothing happens.
I've tried to debug what's going on.
validate(
need(!is.null(itemsData()), "Please select some items")
)
dataC <- itemsData()
browser()
When the execution stops there, I can see that dataC do contains the chosen data.
Console utput of options(shiny.trace=TRUE) is talkative but I cannot really understand what it tries to tell me. Here's a snippet from the last message when the chart ought to render with new data, but does not.
SEND {"errors":[],"values":{"chart":"<style>.rChart {width: 800px;
height: 400px} </style>\n<script type='text/javascript'>\n
$(document).ready(function(){\n drawchart()\n });\n
function drawchart(){ \n var opts = {\n \"dom\":
\"chart\",\n\"width\": 800,\n\"height\": 400,\n\"x\":
\"id\",\n\"y\": \"value\",\n\"group\": \"variable\",\n\"type\":
\"multiBarChart\",\n\"id\": \"chart\" \n},\n data =
[ TEXT CUT OFF ] drawchart(){ \n n return chart;\n
});\n };\n</script>"},"inputMessages":[]}
Again, data= includes the correct, chosen data.
Is something wrong with my reactive values?
EDIT after observation: if I delete all selected item(s) before switching to another School, this works.
So, after some trial & error, this looks promising:
itemsData <- reactive({
if( is.null(input$items) ){
return(NULL)
}
isolate(selectedSchoolData()[selectedSchoolData()$Title %in%
input$items, ])
})
but I haven't yet got my head over isolate() so if someone could explain, why this works, I'd be grateful.
I decided to go with this.
itemsData <- reactive({
if( is.null(input$items) ){
return(NULL)
}
isolate(selectedSchoolData()[selectedSchoolData()$Title %in%
input$items, ])
})
I am attempting to extract tables from very large text files (computer logs). Dickoa provided very helpful advice to an earlier question on this topic here: extracting table from text file
I modified his suggestion to fit my specific problem and posted my code at the link above.
Unfortunately I have encountered a complication. One column in the table contains spaces. These spaces are generating an error when I try to run the code at the link above. Is there a way to modify that code, or specifically the read.table function to recognize the second column below as a column?
Here is a dummy table in a dummy log:
> collect.models(, adjust = FALSE)
model npar AICc DeltaAICc weight Deviance
5 AA(~region + state + county + city)BB(~region + state + county + city)CC(~1) 17 11111.11 0.0000000 5.621299e-01 22222.22
4 AA(~region + state + county)BB(~region + state + county)CC(~1) 14 22222.22 0.0000000 5.621299e-01 77777.77
12 AA(~region + state)BB(~region + state)CC(~1) 13 33333.33 0.0000000 5.621299e-01 44444.44
12 AA(~region)BB(~region)CC(~1) 6 44444.44 0.0000000 5.621299e-01 55555.55
>
> # the three lines below count the number of errors in the code above
Here is the R code I am trying to use. This code works if there are no spaces in the second column, the model column:
my.data <- readLines('c:/users/mmiller21/simple R programs/dummy.log')
top <- '> collect.models\\(, adjust = FALSE)'
bottom <- '> # the three lines below count the number of errors in the code above'
my.data <- my.data[grep(top, my.data):grep(bottom, my.data)]
x <- read.table(text=my.data, comment.char = ">")
I believe I must use the variables top and bottom to locate the table in the log because the log is huge, variable and complex. Also, not every table contains the same number of models.
Perhaps a regex expression could be used somehow taking advantage of the AA and the CC(~1) present in every model name, but I do not know how to begin. Thank you for any help and sorry for the follow-up question. I should have used a more realistic example table in my initial question. I have a large number of logs. Otherwise I could just extract and edit the tables by hand. The table itself is an odd object which I have only ever been able to export directly with capture.output, which would probably still leave me with the same problem as above.
EDIT:
All spaces seem to come right before and right after a plus sign. Perhaps that information can be used here to fill the spaces or remove them.
try inserting my.data$model <- gsub(" *\\+ *", "+", my.data$model) before read.table
my.data <- my.data[grep(top, my.data):grep(bottom, my.data)]
my.data$model <- gsub(" *\\+ *", "+", my.data$model)
x <- read.table(text=my.data, comment.char = ">")