[R] Retaining variable name in a function

Sarah Goslee sarah.goslee at gmail.com
Wed Mar 17 20:19:23 CET 2010


How about this? It changes a column to a factor, and
optionally renames it.

facts <- function(meta, mod, newmodname) {
   meta[,mod] <- factor(meta[,mod])
   if(!missing(newmodname)) {
      colnames(meta)[colnames(meta) == mod] <- newmodname
   }
   meta
}

> testdata <- data.frame(a=c(1,2,3), b=c(1,1,2))
> str(testdata)
'data.frame':	3 obs. of  2 variables:
 $ a: num  1 2 3
 $ b: num  1 1 2
>
> test1 <- facts(testdata, "a")
> str(test1)
'data.frame':	3 obs. of  2 variables:
 $ a: Factor w/ 3 levels "1","2","3": 1 2 3
 $ b: num  1 1 2
>
> test2 <- facts(testdata, "b", "newb")
> str(test2)
'data.frame':	3 obs. of  2 variables:
 $ a   : num  1 2 3
 $ newb: Factor w/ 2 levels "1","2": 1 1 2

Sarah

On Wed, Mar 17, 2010 at 3:06 PM, AC Del Re <delre at wisc.edu> wrote:
> Hi All,
>
> Im interested in creating a function that will convert a variable within a
> data.frame to a factor while retaining the original name (yes, I know that I
> can just:  var <-factor(var) but I need it as a  function for other
> purposes). e.g.:
>
> # this was an attempt but fails.
>
> facts <- function(meta, mod, modname = "spec") {
>  meta$mod <- factor(meta$mod)
>  colnames(meta)['mod'] <- modname
>  return(meta)
> }
>
> # ideally, would like to just specify the data.frame (=meta) and
> # variable to convert to factor (=mod) (similar to function input below).
> But am
> # also interested in having the option to create a new variable and
> # name (similar to the function input above).
>
> facts <- function(meta, mod) {
>  meta$mod <- factor(meta$mod)
>  return(meta)
> }
>
> Thanks for any help!
>
> AC
>

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list