Reputation: 141
I have a function called plot()
. I want my function to be in a way such that if the user just inputs plot()
it will plot all the rows in the data that is read inside the function ( inside plot()
data will be read )
I also want the user to be able to choose which rows he wants to plot from the data. So if the user inputs plot(1)
, function will plot the first row. If user inputs plot(1,3)
it'll plot the first and the third rows.
I tried doing that but I'm not sure how.
This is what I tried to do:
plot <- function(x){
if(x==0)
{ //reads the whole file and plots all the rows
}
else
{
//reads the specified rows and plots them
}
}
This works only if the user wants to plot one row as in the case of plot(1)
, but doesn't work if the user wants more than one row (i.e plot(1,2,3)
).
Help?
Upvotes: 1
Views: 33
Reputation: 6685
test <- function(...){
rows <- c(...)
if(!is.null(rows) & !is.integer(rows)){stop("Input is not an integer"!)}
if(max(rows) > nrow(data)){stop("Out of bounds!")}
if(is.null(rows)){
plot(data)
}else{
plot(data[rows,])
}
}
The ...
lets you put in anything you want, so this will need some error prevention.
The function just creates a vector of the input, checks for length to see if input was given, then plots either the whole dataset (no input given) or the lines determined by the vector rows
.
Edit: Changed first error prevention from numeric
to integer
.
In the long run, you will probably need more error prevention with this kind of input, but for now it should work.
Upvotes: 2