Mohit Sharma: LinkedIn, Twitter
GitHub Site, Repository
Is x
a dataframe of column one or a numeric vector?
x = mtcars[, 'mpg']
x
is a numeric vector.
x = mtcars[,'mpg']
is.vector(x, mode='numeric')
## [1] TRUE
To get dataframe after subsetting, use the argument drop=FALSE
.
x = mtcars[,'mpg', drop=FALSE]
class(x)
## [1] "data.frame"
This behaviour can often be source of bugs when writing a code pipeline, as intuitively you would expect it to return a one column dataframe. To avoid flattening of subsets, remember to use drop=FALSE
.
Other option could be to use tibble
, which always return a tibble.
mtcars = dplyr::as_tibble(mtcars)
x = mtcars[, 'mpg']
class(x)
## [1] "tbl_df" "tbl" "data.frame"
Thanks for reading. If you like the question, how about a tip: PayPal TipJar