1
votes

In a knitr presentation using LaTeX/beamer, I want to illustrate the sem package, where several functions internally use scan() to read and then parse data and model specifications.

The following chunk gives a knitr error

<<union1>>=
library(sem)
union <- readMoments(diag=TRUE,
         names=c('y1', 'y2', 'y3', 'x1', 'x2'))
    14.610
    -5.250  11.017
    -8.057  11.087   31.971
    -0.482   0.677    1.559   1.021
   -18.857  17.861   28.250   7.139  215.662

@

shown here:

 <text>:5:13: unexpected numeric constant
4:           14.610
5:     -5.250  11.017
           ^    

Even if I use eval=FALSE in the chunk, I get an error, but I do get some reasonable output to the PDF file.

Another example, also giving errors is this chunk to specify a sem model:

<<union2, eval=FALSE >>=
union.mod <- specifyEquations(covs=c("x1", "x2"))
y1 = gam12*x2
y2 = beta21*y1 + gam22*x2
y3 = beta31*y1 + beta32*y2 + gam31*x1

@

These all work in an R console. How can they be done using knitr?

I understand why scan() doesn't work in chunks and how to get around this using the text argument, but I don't know how to work around this problem when a function called in a chunk uses scan() internally.

I also understand that I could put the data in a file, union.txt and use something like

<<union1>>=
library(sem)
union <- readMoments(file='union.txt', diag=TRUE,
         names=c('y1', 'y2', 'y3', 'x1', 'x2'))
@

but then I don't know how to display the contents of this file in a chunk in the presentation.

1

1 Answers

1
votes

John Fox pointed out that the development version of the sem package on R-Forge now includes a text argument that simplifies this by reading from a textConnection. I can now use this as:

<<union1, size='footnotesize' >>=
library(sem)
union <- readMoments(diag=TRUE,
         names=c('y1', 'y2', 'y3', 'x1', 'x2'),
         text="
    14.610
    -5.250  11.017
    -8.057  11.087   31.971
    -0.482   0.677    1.559   1.021
   -18.857  17.861   28.250   7.139  215.662
")
@