If I subset to extract a variable from a data frame in base R, I would run
mtcars[, "cyl"]
which returns a vector.
For two variables it would be
mtcars[, c("cyl","am")]
which returns a data frame.
How can I ensure consistency to always return a data frame without doing this?
function(data = mtcars, vars = "cyl") {
mydata <- data[, "cyl"]
if (class(mydata) != "data.frame") {
mydata <- as.data.frame(mydata)
}
return(mydata)
}
I know that dplyr is consistent but I prefer to use base R for this
library(dplyr)
function(data = mtcars, vars = "cyl") {
mydata <- data %>%
select(vars)
return(mydata)
}