Reputation: 45
I want to create a function with optional parameters. I am working on a dataset with income, states, and a few flags. The function takes the data, state and flag and filters it. If state and flag is missing, it should return the entire data, and so on. So far I have this code which is working fine. However, I want to know if there is a simpler code than this.
myfun <- function(data, states, flag){
if(missing(states)) {
if(missing(flag)) {
new_data <- data
} else {
new_data <- subset(data, data$Flag == flag)
}
} else if(missing(flag)) {
new_data <- subset(data, data$State == states)
} else {
new_data <- subset(data, (data$State == states & data$Flag == flag))
}
temp_data <- toJSON(new_data)
save(temp_data, file = "Mydata.JSON")
return(new_data)
}
I know we can have optional parameters by having a default parameter like flag = Y
. But how do I pass both the parameters in default parameters i.e. flag = Y & N
, or all the 50 states. I am new to R and any help would be greatly appreciated.
Update: Got a solution I was looking for thanks to Daniel Winkler
test2 <- function(data,states = unique(data$State),flag = c("Y","N"))
{my_data<-subset(data, (data$State %in% states & data$Flag %in% flag))}
Upvotes: 2
Views: 89
Reputation: 497
For passing multiple values to the function:
myfun<-function(data,states,flag){
if(missing(states))
{
if(missing(flag))
{
new_data<-data
}
else
{
new_data<-subset(data, data$Flag %in% flag)
}
}
else if(missing(flag))
{
new_data<-subset(data, data$State %in% states)
}
else
{
new_data<-subset(data, (data$State %in% states & data$Flag %in% flag))
}
temp_data <- toJSON(new_data)
save(temp_data, file="Mydata.JSON")
return(new_data)
}
Then call with:
all_states <- unique(mydata$States)
myfun(data = mydata, states = all_states, flag = c('Y', 'N'))
Upvotes: 1