[R] R Markdown and scan()

John Fox jfox at mcmaster.ca
Sat Oct 25 17:58:28 CEST 2014


Dear Peter,

Thanks for the suggestion -- it's a bit better for the example I provided than my approach of using textConnection() of putting the lines in a file. 

I'd still be interested in whether I've missed something like a text-chunk option that would allow the R Markdown document to behave like a script executed at the console. For example, your approach doesn't work for the application where I encountered the problem, which is in a function that calls scan() and that passes the file argument to it, but doesn't use the text argument.

Best,
 John

On Sat, 25 Oct 2014 17:11:14 +0200
 peter dalgaard <pdalgd at gmail.com> wrote:
> 
> > On 25 Oct 2014, at 16:43 , John Fox <jfox at mcmaster.ca> wrote:
> > 
> > Dear JJ and list members,
> > 
> > I wonder whether it's possible to get scan() to read in-line data in an R Markdown document. The following code, for example, works (of course) when entered in the R console but fails in an R block in an R Markdown document (using an up-to-date version of RStudio):
> > 
> > ```{r}
> > x <- scan()
> > 1 2 3
> > 4 5 6
> > 
> > x
> > ````
> > 
> > I'm aware of a couple of work-arounds, such as putting the data in a file or a character string (as below), but am interested in whether it's possible to get this to work directly.
> > 
> > ```{r}
> > text <- "
> > 1 2 3
> > 4 5 6
> > "
> > (x <- scan(file=textConnection(text)))
> > ````
> > 
> > Any help would be appreciated.
> 
> This generally isn't easy. You can't source() a file like that either, it only works on std.input, and even there it is tricky it you have tabs in the (pasted) data. Notice that
>  
> scan(text="
> 1 2 3
> 4 5 6
> ")
> 
> was designed for the purpose of reading inline data.
> 
>  
> -- 
> Peter Dalgaard, Professor,
> Center for Statistics, Copenhagen Business School
> Solbjerg Plads 3, 2000 Frederiksberg, Denmark
> Phone: (+45)38153501
> Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com
> 
>



More information about the R-help mailing list