I'm working in R and I need to re-run a region of the code that is written above the line where I 'm working at. I mean, just a specific part of the code, a few lines. For example :
1 x <- c(0:10)
2
3 #Start of region to rerun ----------------------
4
5 y <- c(0,1,0,0,2,2,3,3,4,4,5)
6 z <- c(rep(100,3), rep(200, 3), rep(300,5))
7 table <- cbind(x,y,z)
8
9 #End of region to rerun ------------------------
10
11
12 plot(table, type = "o") #plot numer1
13
14 #Modification of one variable
15 x <- x*1.5
16
17 # I would like tu rerun the region above, form line 3 to line 9
18
19
20 plot(table, type = "o") #plot numer2
Thank you for your help!
I assume you want to rerun the code because you changed the value of x, right?
also you do not seem to need the variables of x
and y
further.
Therefore a function might be ideal for you:
make_my_table <- function(x){
y <- c(0,1,0,0,2,2,3,3,4,4,5)
z <- c(rep(100,3), rep(200, 3), rep(300,5))
table <- cbind(x,y,z)
# return says to return this variable, if the function is called
return(table)
}
x <- c(0:10)
# first Plot
# make_my_table(x) will execute the function with the value for x and return the table
plot(make_my_table(x), type = "o")
# change of x
x <- 1.5*x
# second plot
plot(make_my_table(x), type = "o")
I dont know how often you want to repeat the plot, but if there is a defined series of x
values, you can execute the plot function within a for
-loop or a lapply
-loop, as the other answer suggest. I just wanted to explain how one can actively rerun a certain piece of code.
The advantage of a function is that except for the return variable, all variables within the function are deleted, so they do not clog your environment and confuse you.