Saran
Saran

Reputation: 713

What is the difference between executing and sourcing scripts in R

A basic question as I am starting out R.

What is the main difference when I am sourcing a R script vs executing it? I am trying to get ggplot2 example scripts running.

library("ggplot2")

d = data.frame(x1=c(1,3,1,5,4), x2=c(2,4,3,6,6), y1=c(1,1,4,1,3), y2=c(2,2,5,3,5), t=c('a','a','a','b','b'), r=c(1,2,3,4,5))
ggplot() +
scale_x_continuous(name="x") +
scale_y_continuous(name="y") +
geom_rect(data=d, mapping=aes(xmin=x1, xmax=x2, ymin=y1, ymax=y2, fill=t),color="black",alpha=0.5) +
geom_text(data=d, aes(x1+(x2-x1)/2,y=y1+(y2-y1)/2, label=r), size=4) +
opts(title="geom_rect", plot.title=theme_text(size=40, vjust=1.5))

When I source this script, no plots appear. I understand this has to do with lack of explicit print statement in my code. I've read a discussion that when you execute a command in the interactive shell, the print statement is implicit.

My question is this - When I execute a script vs source it, what is the basic difference? When would I do one over another? Thanks!

Upvotes: 4

Views: 1896

Answers (1)

IRTFM
IRTFM

Reputation: 263451

This seems likely to be related to The R-FAQ in section 7 relating to why grid based graphics do not get plotted. Try using explicit print or plot command.

Reading the first sentence of "Details" in the help page for source to you:

`Details

Note that running code via source differs in a few respects from entering it at the R command line. Since expressions are not executed at the top level, auto-printing is not done.` (And I'm glad to see that you did read the rest of that section.)

Upvotes: 4

Related Questions