Convert string to a variable name
assign is what you are looking for.
assign("x", 5)
x
[1] 5
but buyer beware.
See R FAQ 7.21
http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f
Pass a string as variable name in dplyr::filter
!!
or UQ
evaluates the variable, so mtcars %>% filter(!!var == 4)
is the same as mtcars %>% filter('cyl' == 4)
where the condition always evaluates to false; You can prove this by printing !!var
in the filter function:
mtcars %>% filter({ print(!!var); (!!var) == 4 })
# [1] "cyl"
# [1] mpg cyl disp hp drat wt qsec vs am gear carb
# <0 rows> (or 0-length row.names)
To evaluate var
to the cyl
column, you need to convert var
to a symbol of cyl
first, then evaluate the symbol cyl
to a column:
Using rlang
:
library(rlang)
var <- 'cyl'
mtcars %>% filter((!!sym(var)) == 4)
# mpg cyl disp hp drat wt qsec vs am gear carb
#1 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
#2 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
#3 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
# ...
Or use as.symbol/as.name
from baseR:
mtcars %>% filter((!!as.symbol(var)) == 4)
mtcars %>% filter((!!as.name(var)) == 4)
Convert string to variable name in R
Firstly, it's a backtick (`), not an apostrophe ('). In R, backticks occasionally denote variable names; apostrophes work as single quotes for denoting strings.
The issue you're having is that your variables start with a number, which is not allowed in R. Since you somehow made it happen anyway, you need to use backticks to tell R not to interpret 2011_Q4
as a number, but as a variable.
From ?Quotes
:
Names and Identifiers
Identifiers consist of a sequence of letters, digits, the period (.)
and the underscore. They must not start with a digit nor underscore,
nor with a period followed by a digit. Reserved words are not valid
identifiers.The definition of a letter depends on the current locale, but only
ASCII digits are considered to be digits.Such identifiers are also known as syntactic names and may be used
directly in R code. Almost always, other names can be used provided
they are quoted. The preferred quote is the backtick (`), and deparse
will normally use it, but under many circumstances single or double
quotes can be used (as a character constant will often be converted to
a name). One place where backticks may be essential is to delimit
variable names in formulae: see formula.
The best solution to your issue is simply to change your variable names to something that starts with a character, e.g. Y2011_Q4
.
How to use character as variable name in arguments? [R]
We could use setNames
out <- do.call(dict, setNames(rep(list(1), length(x)), x))
out$keys
[1] "1" "2"
Or we may use invoke
or exec
library(purrr)
out <- invoke(dict, setNames(rep(1, length(x)), x))
out <- exec(dict, !!!setNames(rep(1, length(x)), x))
For the second case, also setNames
works
setNames(list(1), y)
$happy
[1] 1
or we can use dplyr::lst
dplyr::lst(!! y := 1)
$happy
[1] 1
R - use function argument as variable name and string value
Here, it may be better to use .data
with [[
to subset instead of {{}}
as the input passed is character string
testfun <- function(modelnum){
covars <- modelinfo %>%
filter(.data[[modelnum]]==1)
data <- modeldata %>%
filter(model==modelnum)
output=c(covars,data)
return(output)
}
-testing
testfun(modelnum="model 1")
$covars
[1] "x1"
$`model 1`
[1] 1
$`model 2`
[1] 0
$x1
[1] 3 1
$x2
[1] 3 3
Pass a string as variable name in dplyr::mutate
This operation can be carried out with :=
while evaluating (!!
) and using the conversion to sym
bol and evaluating on the rhs of assignment
library(dplyr)
my_mtcars <- mtcars %>%
mutate(!! var := factor(!! rlang::sym(var)))
class(my_mtcars$vs)
#[1] "factor"
Or without thinking too much, use mutate_at
, which can take strings in vars
and apply the function
of interest
my_mtcars2 <- mtcars %>%
mutate_at(vars(var), factor)
Related Topics
Align Edges of Ggplot Choropleth (Legend Title Varies)
Can Lapply Not Modify Variables in a Higher Scope
Setting Ld_Library_Path from Inside R
Efficient Apply or Mapply for Multiple Matrix Arguments by Row
Change Color Actionbutton Shiny R
Use a Factor Column in "By" and Do Not Drop Empty Factors
How to Remove All Rows from a Data.Frame
Dplyr Count Number of One Specific Value of Variable
Include Zero Frequencies in Frequency Table for Likert Data
Saving a Data Frame as a Binary File
Rotate Labels in a Chorddiagram (R Circlize)
Shade (Fill or Color) Area Under Density Curve by Quantile
How to Retrieve the Most Repeated Value in a Column Present in a Data Frame
Specifying the Scale for the Density in Ggplot2's Stat_Density2D