Visualizzazione post con etichetta converting. Mostra tutti i post
Visualizzazione post con etichetta converting. Mostra tutti i post

mercoledì 16 maggio 2007

How can I turn a string into a variable?

If you have

varname <- c("a", "b", "d")

you can do

get(varname[1]) + 2

for a + 2

or

assign(varname[1], 2 + 2)

for a <- 2 + 2

or

eval(substitute(lm(y ~ x + variable), list(variable = as.name(varname[1]))

for lm(y ~ x + a)

At least in the first two cases it is often easier to just use a list, and then you can easily index it by name

vars <- list(a = 1:10, b = rnorm(100), d = LETTERS) vars[["a"]]

without any of this messing about.