[R] how to transform string to variable name in a fuction?

Wensui Liu liuwensui at gmail.com
Wed Dec 27 04:05:54 CET 2006


try ?assign

On 12/26/06, jingjiangyan <jingjiangyan at gmail.com> wrote:
> there is a data frame, like this:
> > df
>   aa       bb
> 1  a     20.27802
> 2  b     22.10664
> 3  c     21.33470
> 4  a     22.32898
> 5  b     19.73760
> 6  c     20.38979
> .....(suppressed)
> what I want to do is to copy the data frame's rows into different data frames according to the levels of 'aa' column,
> > df.a <- df[df[,1]=='a',] ; df.b <- df[df[,1]=='b',] ; ....
> > df.a
>   aa       bb
> 1  a 20.27802
> 4  a 22.32898
> ...
>
> So, when completed, there should be df.a, df.b,df.c, etc.
> If we could do this by hand, it is pretty fine.  But could I write a loop to do this ?
> when I tried this using a funciton, there is a problem.
>
> > for ( i in levels(df[,1])) {
> +  name = paste('df',i,sep='')
> +  name <- df[df[,1]==i,]
> + }
> > name
>   aa       bb
> 3  c 21.33470
> 6  c 20.38979
> > ls()
> [1] "df"   "i"    "name"
> > i
> [1] "c"
> there is not data frames df.a, df.b,etc.
>
> Could you please give me some suggestion?
> I have found that write a function in R for a beginner is difficult. Is there  any tutorial on writing the functions in R?
> Furthermore, someone also said that loop is not used as frequently as in other script language (e.g. bash, perl). So, If you have any other smart means do this more efficiently, please let me know, I would appreciate your kindness.
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch 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.
>


-- 
WenSui Liu
A lousy statistician who happens to know a little programming
(http://spaces.msn.com/statcompute/blog)



More information about the R-help mailing list