Reputation: 538
I was wondering if there is a way to select multiple variables while writing a code. I mean when we type the dataframe name followed by $, we get the list of all variables but it only allows selecting one at a time.
Is there a way (like a package or rstudio add in) that allows selecting multiple?
what I have been doing so far is (and I got the ideas from this 2012 post ):
dput(names(dataframe))
then select what I needwith all these nice rstudio add ins around, I was hoping there is a nicer/ more efficient way to select the variables without having to type them individually.
this sounds like a basic question and I apologize in advance if it has been asked before but I could not find an answer here or on stackoverflow.
thanks a lot
Upvotes: 1
Views: 2783
Reputation: 270348
None of the solutions below are specific to R Studio but are general facilities in R or dplyr.
There must be some way to select them so if there is no common pattern you can list them explicitly or use their positions. Then any of these will select the columns -- in this example mpg
and cyl
columns from mtcars
:
nms <- c("mpg", "cyl")
# or nms <- 1:2
mtcars[nms]
mtcars[, nms]
subset(mtcars, select = nms)
dplyr::select(mtcars, all_of(nms))
or if you want to specify a content related query use one of these:
iris[ sapply(iris, is.numeric) ]
dplyr::select(iris, where(is.numeric))
If what you mean is that you want a GUI to show the available names in a specific data frame so you can interactively select them then use this (see screenshot at end):
select.list(names(mtcars), multiple = TRUE)
or
library(tcltk)
tk_select.list(names(mtcars), multiple = TRUE)
Upvotes: 3