[R] It is possible to use a Shell command inside a R script?

Gabor Grothendieck ggrothendieck at gmail.com
Fri Aug 24 17:41:32 CEST 2007


On 8/24/07, Dirk Eddelbuettel <edd at debian.org> wrote:
> On Fri, Aug 24, 2007 at 08:32:00AM -0400, Duncan Murdoch wrote:
> > On 8/24/2007 6:58 AM, Ronaldo Reis Junior wrote:
> > > Hi,
> > >
> > > It is possible to use a shell command inside a R script?
> > >
> > > I'm write a R script and I like to put somes shell commands inside to R.
> > > Somethink like: convert fig01.png fig01.xpm or sed ..., etc.
> >
> > The details and available functions depend on the platform, but you want
> > to look at ?system, ?shell, and/or ?shell.exec.  (These all exist in
> > Windows; on Unix-alikes, you probably won't have the latter two.)
>
> Don't forget pipes.
>
> R's ability to consistently work on connections that may be local
> files, remotes files, program output, ... is a true treasure (and
> thanks and credits to, I believe, Brian Ripley to make it so).
>
> Eg you can do this
>
>  OD <- read.table(pipe("links -dump http://cran.r-project.org/src/contrib/ | awk '/tar.gz/ {print $3, $4}'"), header=FALSE, col.names=c("file", "date"))
>
> to get files and dates of files on CRAN.
>
> As I recall, this also works on that other operating system, provided
> you do all the legwork of installing other tools, setting PATHs etc
> to provide what works out of the box on the supposedly unfriendlier OS.
>

Or commonly we can just do it entirely within R.  In the example discussed
we read in the lines, grep out the tar.gz lines, split each line into
fields and
select the desired columns, delete the junk and reformat it all into a
data frame:

> Lines <- readLines("http://cran.r-project.org/src/contrib/")
> tar.gz.Lines <- grep("tar.gz", Lines, value = TRUE)
> raw.fields <- do.call(rbind, strsplit(tar.gz.Lines, "</td>"))[, 2:3]
> mat <- apply(raw.fields, 2, gsub, pattern = "</a>|.*\">| *$", replacement = "")
> DF <- data.frame(file = mat[,1],
+   date = strptime(mat[,2], "%d-%b-%Y %H:%M"),
+   stringsAsFactors = FALSE)
> head(DF)
                             file                date
1             ADaCGH_1.3-1.tar.gz 2007-05-14 12:04:00
2                  AIS_1.0.tar.gz 2007-07-31 16:38:00
3             AMORE_0.2-10.tar.gz 2007-04-11 10:17:00
4               ARES_1.2-2.tar.gz 2007-03-19 20:53:00
5 AcceptanceSampling_0.1-1.tar.gz 2007-07-07 20:46:00
6           AdaptFit_0.2-1.tar.gz 2007-08-04 09:51:00



More information about the R-help mailing list