Wow, wonderful! Thank you for all the response -- and so quick!

ac



On Wed, Mar 17, 2010 at 2:19 PM, Sarah Goslee <[email protected]>
 wrote:

> 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 2:23 PM, Henrique Dallazuanna <[email protected]>wrote:

> Try this:
>
> transform(DF, newA = factor(a), a = NULL)
>
> On Wed, Mar 17, 2010 at 4:06 PM, AC Del Re <[email protected]> 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
> >
> >        [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > [email protected] 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.
> >
>
>
>
> --
> Henrique Dallazuanna
> Curitiba-Paraná-Brasil
> 25° 25' 40" S 49° 16' 22" O
>

        [[alternative HTML version deleted]]

______________________________________________
[email protected] 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.

Reply via email to