Search code examples
rloopslatexr-markdownpdf-generation

Including space between two variables in a for loop r markdown (pdf output)


I am trying to create some stimuli using R Markdown, and for each trial I intend to extract two values from two columns (L_Prob & R_Prob) in a data frame (D1) and to present them side by side. I intend to output the r markdown file into pdf. I also intend to include some spaces between the two values; however, I am having difficulty. My current code looks like below.

{r, echo = F, comment=NA, results='asis'}
D1= data.frame(L_Prob=c("a+b","b+c","c+d"),R_Prob=c("d+e","e+f","f+g"))

for (i in 1:nrow(D1)){

  a = D1%>% select(L_Prob) %>% slice(i) %>% pull
  b = D1%>% select(R_Prob) %>% slice(i) %>% pull
  cat(a,b)
  cat("  \n") 
  cat("Why do you choose this problem?")
  cat("  \n") 
  cat("It looks to be easier to solve")
  cat("  \n") 
  cat("I prefer problems in this number type")
  cat("  \n") 
  cat("No particular reason")
  cat("  \n") 
  cat("Other______________________________")
  cat("\\newpage  ")
}

The output looks like a+b b+c with no space between. What I want it to look like is

a+b                                 b+c

I have tried cat(a," ",b) which doesn't work. I am not sure exactly how I can do it and any suggestion would be appreciated. Since I am outputting it into pdf, my understanding is that I cannot left align a and right align b, but, please correct me if I am wrong. Thank you again for your help!


Solution

  • LaTeX ignores spaces by default. Try \hspace{length}:

    cat(a, "\\hspace{10em}", b)
    

    More on length units. Play with it until you reach the desired result. Or use \space:

    cat(a,rep("\\space", 33),b)
    

    enter image description here