[R] Object name vectcor as function input argument?
Charles C. Berry
cberry at tajo.ucsd.edu
Sat Dec 27 21:26:22 CET 2008
On Sat, 27 Dec 2008, Sean Zhang wrote:
> Dear R-helpers:
>
> I am new to R and ran into the following question and would appreicate
> your advice very much.
>
> My question: How to use a character vector that records object names as
> function input argument?
>
> I asked this question very recently and was advised to use get(). get()
> works when passing one single object name.
> but it does not work when passing multiple object names.
>
> For example, I want to rbind many dfs into one df.
> Below, I use 3 data frames for illustration.
> df.1 <- data.frame(v1=rnorm(5), v2=rnorm(5))
> df.2 <- data.frame(v1=rnorm(5), v2=rnorm(5))
> df.3 <- data.frame(v1=rnorm(5), v2=rnorm(5))
>
> all.dfs <- c("df.1","df.2","df.3")
Try this:
> rb.obj <- quote(rbind())
> rb.obj[ all.dfs ] <- lapply( all.dfs, as.name )
> eval(rb.obj)
HTH,
Chuck
> # all.dfs is the a character vector recording all object names and I would
> like to use all.dfs as
> # an input argument for a function that performs rbind
>
> # The following works, but I do not know how to use all.dfs as its input
> argument
> output <- do.call("rbind",list(df.1,df.2,df.3))
>
> # The desired function has the following form:
>
> output <- desired.function (all.dfs)
>
>
> # Show some hw I have done below:
> # I tried the following things and they do not work
> do.call("rbind",list(all.dfs))
>
> one.string <- paste(all.dfs,collapse=",")
>
> do.call("rbind",list(one.string))
> do.call("rbind",list(get(one.string)))
> do.call("rbind",list(parse(one.string)))
> # By the way, the following loop.fun works but it is Not what I like because
> I may have a large number of dfs
> loop.fun <- function (all.dfs)
> {
> for (i in 1:length(all.dfs) )
> ifelse ( i==1, output <- get(all.dfs[i]), output <-
> rbind(output,get(all.dfs[i])) )
> return(output)
> }
>
> output <- loop.fun(all.dfs)
>
>
>
> #Your help is highly appreciated. Many thanks in advance.
>
> -Sean Zhang, Ann Arbor
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cberry at tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
More information about the R-help
mailing list