[R] how to split a data frame by two variables

jim holtman jholtman at gmail.com
Thu Sep 1 19:59:18 CEST 2011


try this:

> split(x, list(x$let, x$g))
$a.1
   num let g
1   10   a 1
11  21   a 1

$b.1
   num let g
7   52   b 1
17  56   b 1

$c.1
   num let g
3   12   c 1
13  32   c 1

$d.1
   num let g
9   12   d 1
19  76   d 1

$e.1
   num let g
5   23   e 1
15  24   e 1



On Thu, Sep 1, 2011 at 1:53 PM, Changbin Du <changbind at gmail.com> wrote:
> HI, Dear R community,
>
> I want to split a data frame by using two variables: let and g
>
>> x = data.frame(num =
> c(10,11,12,43,23,14,52,52,12,23,21,23,32,31,24,45,56,56,76,45), let =
> letters[1:5], g = 1:2)
>> x
>   num let g
> 1   10   a 1
> 2   11   b 2
> 3   12   c 1
> 4   43   d 2
> 5   23   e 1
> 6   14   a 2
> 7   52   b 1
> 8   52   c 2
> 9   12   d 1
> 10  23   e 2
> 11  21   a 1
> 12  23   b 2
> 13  32   c 1
> 14  31   d 2
> 15  24   e 1
> 16  45   a 2
> 17  56   b 1
> 18  56   c 2
> 19  76   d 1
> 20  45   e 2
>
> I tried the following:
>
> xs = split(x,x$g*x$let)
>
> *Warning message:
> In Ops.factor(x$g, x$let) : * not meaningful for factors*
>
>
> xs = split(x,c(x$g*x$let))
>
> *Warning message:
> In Ops.factor(x$g, x$let) : * not meaningful for factors
> *
>
> Can someone give some hints?
>
> Thanks!
>
>
> --
> Sincerely,
> Changbin
> --
>
>        [[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.
>



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?



More information about the R-help mailing list