I have searched SO and found a similar question, but I still can't get it to work.
I am rather new to R programming, so I appreciate this help.
Suppose I have a data.frame
:
df <- data.frame(State = c("NJ", "MA", "CA", "CA", "MA"),
Sales = c(15, 100, 30, 56, 60),
Price = c(34, 52, 21, NA, 20),
stringsAsFactors = FALSE)
Now I want a function that creates a new data.frame
that just has a given state... So I wrote:
state_function <- function(state) {
#Subset the rows in the state from all rows
new_df <- df[df[,"State"] == state, ]
## I will do many other things inside the function ##
summary(new_df)
return(new_df)
}
state_function ("NJ")
But now I want to re-use this data.frame
, new_df
, outside of this function ..(and I want to generalize this example) .. How can I do this? In general, I want to use a object or data.frame
that I create in a function, outside of a function.