string - How to use argument of a function as name of variable? -
i have feeling trivial, , apologize asking such easy questions, appreciate following problem: have function requires 2 arguments:
myfun <- function(fm, name){ ... }
the data frame used can via dat <- eval(fm$call$data)
inside function. inside dat
, there variable name identical second argument, i.e. there variable dat$name
(note second argument of function not include reference dataframe, i.e. name not equal dat$name
name
) , use variable.
q: how can that?
concrete example: following serves example:
air <- data(airquality) fm <- lm(ozone ~ solar.r, data=airquality) myfun <- function(fm, name){ df <- eval(fm$call$data) name[1:5] } myfun(fm, temp)
the purpose of function show first 5 elements of variable name
in dataframe has been used fitting fm
. however, name
not recognized variable in corresponding data frame. neither wrapping with(df, ...)
, df$name
or equivalent solutions trick. how work?
edit: have played around bit further still not working. thought should work after inspired of comments:
myfun <- function(fm, name){ df <- as.character(fm$call$data) varname <- deparse(substitute(name)) d1 <- paste(df, "$", sep="") d2 <- paste(d1, varname, sep="") get(d2)[1:5] } myfun(fm, temp)
this produces character string called airquality$temp
, following error: error in get(d2): object 'airquality$temp' not found.
hoping constructing string gives me name of variable including data frame access using get
, still not work... :(
using example,
air <- data(airquality) fm <- lm(ozone ~ solar.r, data=airquality) myfun <- function(fm, name){ dn <- fm$call[['data']] varname <- deparse(substitute(name)) get(as.character(dn),envir=.globalenv)[varname] } myfun(fm, temp)
Comments
Post a Comment