I am trying to understand the difference between <-
and <<-
in practice. I wrote the following function in R
that relies on a couple of other small function that I wrote:
fun.exec <- function(x=dat){
id1 <- prompt1()
id2 <- prompt2()
el.type <- data.switch(di=id1)
dat.sifted <- data.sift(x, nc=id2)
plots.list <- evol.tiles(ds=dat.sifted, dt=el.type, nc=id2)
p <- evol.plot(l=plots.list, dt=el.type)
}
Functions prompt1
and prompt2
take an input from a user, el.type()
assigns string name to the data (for use in describing different plots automatically), data.sift()
extract relevant data from a big data frame object, evol.tiles()
generates various ggplots to be organized in a grid, and evol.plot()
puts the plots in a grid.
As can be seen, both data.sift()
and evol.tiles()
functions use the id2
user's input. When I execute this function as is, I get an error:
Error in evol.tiles(ds = dat.sifted, dt = el.type, nc = id2) : object
'id2' not found
If I replace id2 <- prompt2()
with id2 <<- prompt2()
, the code works as expected.
What I don't understand is why, as is, the code does not break on the data.sift()
function, which also calls for id2
. I read help for assignments, a couple of related posts on StackOverflow, and the Scope section from An Introduction to R but I am still not sure what the problem is. It's almost as if after being used in data.sift()
the variable was no longer available in the environment and I don't understand that is.
Any help will be greatly appreciated.
UPDATE: Here is the code for prompts:
prompt1 <- function(){
cat('What do you want to create plots for? Your options are:
1: data type A,
2: data type B,
3: data type C')
readline(prompt="Enter an integer: ")
}
prompt2 <- function(){
cat('How many nodes do you want to visualize?')
n <- readline(prompt="Enter an integer: ")
cat('\nProvide coordinates of each node to visualize separated by commas.')
l <- vector("list", n)
for (i in 1:n){
el <- readline(prompt=paste('Enter coordinnates for node',i,': '))
l[[i]] <- el
}
return(l)
}
for data.sift()
:
data.sift <- function(x, nc){
nl <- lapply(nc, function(l){as.integer(unlist(strsplit(l,",")))})
ds <- vector("list", length(nl))
for (i in 1:length(nl)){
ds[[i]] <- x[(x$x == nl[[i]][1] & x$y == nl[[i]][2] & x$z == nl[[i]][3]),]
}
return(ds)
}
and for evol.tiles()
:
evol.tiles <- function(ds, dt, nc){
require(ggplot2)
my.cols <- rainbow(length(ds))
my.names <- as.character(nc)
names(my.cols) <- my.names
my.list <- list()
for (i in 1:6){
for (ii in 1:length(id2)){
p <- ggplot(NULL, aes_(x = as.name(names(ds[[ii]][4]))))
p <- p + geom_line(data = ds[[ii]],
aes_(y = as.name(names(ds[[ii]][i])),
colour = as.character(nc[[ii]])))
}
p <- p + scale_colour_manual("Node",
breaks = as.character(nc),
values = my.cols)
my.list[[i-dr[1]+1]] <- p
}
return(my.list)
}