[R] creating a function

Duncan Murdoch murdoch at stats.uwo.ca
Tue Apr 17 02:42:34 CEST 2007


On 4/16/2007 8:19 PM, jiho.han wrote:
> Dear R-experts,
> 
> This should be a simple question, but I couldn't find a way yet. 
> I would like to create a function that accepts a vector, creates a
> data.frame whose colname is that vector. For example, I want a function
> temp.func() such that:
> 
>> name = c( "mike", "john", "steve")
>> result = temp.func(name)
>> result
>         name
> 1       mike
> 2       john
> 3      steve
> 
> Right now I have the following code:
> 
> temp.func = function (x) {
>     x = as.data.frame(x)
>     return(x)
> }
> 
> The problem is, the above function returns the colname, "factor(x)," which
> is not "name." Anyone has Any idea? 

This should work:

temp.func <- function(x) {
    result <- data.frame(x)
    names(result) <- deparse(substitute(x))
    return(result)
}

Duncan Murdoch



More information about the R-help mailing list