[R] plot by cathegories within a factor

Peter Ehlers ehlers at ucalgary.ca
Wed Oct 27 12:54:38 CEST 2010


On 2010-10-27 03:17, Ivan Calandra wrote:
> Hi,
>
> The best I've found (but definitely not the best!):
>
> x<- read.table(textConnection("Group Ind Age Trait
> 1 1 2 21
> 1 2 1 22
> 1 2 2 21
> 1 3 1 24
> 1 3 2 45
> 1 4 1 23
> 1 4 2 26
> 2 1 1 45
> 2 1 2 12
> 2 2 1 25
> 2 2 2 26
> 2 3 1 45
> 2 3 2 43
> 2 4 1 23
> 2 4 2 47
> "), header=T)
>
> str(x)
> 'data.frame':   15 obs. of  4 variables:
>    $ Group: int  1 1 1 1 1 1 1 2 2 2 ...
>    $ Ind  : int  1 2 2 3 3 4 4 1 1 2 ...
>    $ Age  : int  2 1 2 1 2 1 2 1 2 1 ...
>    $ Trait: int  21 22 21 24 45 23 26 45 12 25 ...
>
> x_grp<- split(x, x$Group)
>
> for (i in 1:length(x_grp)){
>    plot(x_grp[[i]]$Trait~x_grp[[i]]$Age)
> }
>
> There are probably better approaches using lattice.
>
> HTH,
> Ivan
>

Using base graphics, we could use the subset argument:

  plot(Trait ~ Age, data = x, subset = {Group == 1})
  plot(Trait ~ Age, data = x, subset = {Group == 2})

perhaps preceded by

  par(mfrow = c(1,2))

With lattice:

  xyplot(Trait ~ Age | Group, data = x)

(I suspect that both Group and Age should really be factors,
which would improve the plot.)

   -Peter Ehlers

>
> Le 10/27/2010 11:21, Rosario Garcia Gil a écrit :
>> Hello
>>
>> I have a data set summarized like this:
>>
>> File name= Height
>>
>> Group Ind Age Trait
>> 1     1	1	20
>> 1	1	2	21
>> 1	2	1	22
>> 1	2	2	21
>> 1	3	1	24
>> 1	3	2	45
>> 1	4	1	23
>> 1	4	2	26
>> 2	1	1	45
>> 2	1	2	12
>> 2	2	1	25
>> 2	2	2	26
>> 2	3	1	45
>> 2	3	2	43
>> 2	4	1	23
>> 2	4	2	47
>> .
>> .
>> .
>>
>>
>> I would like to plot Trait ~ Age but a different plot for each Group.
>> I tried:
>>> plot(Height$Trait ~ Height$Age | Group)
>> But does not work. Any suggestion?
>>
>> Thanks
>> Rosario
>>



More information about the R-help mailing list