[R] Handling repeated values differently

Ali Tofigh alix.tofigh at gmail.com
Fri Mar 12 21:42:12 CET 2010


Here is a suggestion:

tapply(mat[,2], as.factor(m[,1]), sum)

Cheers,
/Ali

On Fri, Mar 12, 2010 at 15:28, Juliet Ndukum <jpntsang at yahoo.com> wrote:
> mat is a matrix with X and Y values.
>> mat
>       X  Y
>  [1,] 56 20
>  [2,] 56 21
>  [3,]  2 50
>  [4,]  3 46
>  [5,] 18 77
>  [6,] 57 12
>  [7,] 57 36
>  [8,] 95 45
>  [9,] 65 23
> [10,] 33 25
> [11,] 33 98
> [12,] 63 96
> [13,] 66 75
> [14,] 99 54
> [15,] 78 65
> [16,] 75 69
> [17,] 54 68
> [18,] 54 67
> [19,]  0 22
> [20,] 14 74
> [21,] 15 52
> [22,] 46 10
> [23,]  6 20
> [24,]  6 30
>
> As you can see, some of the X values repeat. I wish to maintain only one of the X values that is repeated, however, I would like to have the sum of the corresponding Y values. For example, the X value of 6 repeats, with values 20 and 30. In the output, I would like to have 6 as X value, with the corresponding Y value of 50 (20+30).
>
> The output from mat above should be:
>> mat1
>      X1    Y1
>  [1,] 56  41.0
>  [2,]  2  50.0
>  [3,]  3  46.0
>  [4,] 18  77.0
>  [5,] 57  48.0
>  [6,] 95  45.0
>  [7,] 65  23.0
>  [8,] 33 123.0
>  [9,] 63  96.0
> [10,] 66  75.0
> [11,] 99  54.0
> [12,] 78  65.0
> [13,] 75  69.0
> [14,] 54  67.5
> [15,]  0  22.0
> [16,] 14  74.0
> [17,] 15  52.0
> [18,] 46  10.0
> [19,]  6  50.0
>
> I have not been able to come up with a code, I was wondering if someone can help me with a code to handle this.
>
> Thank you in advance for your help,
> JN
>
>
>
>        [[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.
>



More information about the R-help mailing list