[R] means in tables
Marc Schwartz
marc_schwartz at me.com
Wed Apr 10 22:04:34 CEST 2013
On Apr 10, 2013, at 11:07 AM, Silvano Cesar da Costa <silvano at uel.br> wrote:
> Hi.
>
> I have 2 tables, with same dimensions (8000 x 5). Something like:
>
> tab1:
>
> V1 V2 V3 V4 V5
> 14.23 1.71 2.43 15.6 127
> 13.20 1.78 2.14 11.2 100
> 13.16 2.36 2.67 18.6 101
> 14.37 1.95 2.50 16.8 113
> 13.24 2.59 2.87 21.0 118
>
> tab2:
>
> V1 V2 V3 V4 V5
> 1.23 1.1 2.3 1.6 17
> 1.20 1.8 2.4 1.2 10
> 1.16 2.6 2.7 1.6 11
> 1.37 1.5 2.0 1.8 13
> 1.24 2.9 2.7 2.0 18
>
> I need generate a table of averages, the elements in the same position in
> both tables, like:
>
> tab3:
> (14.23 + 1.23)/2 (1.71+1.1)/2 (127+17)/2
>
> and so on
>
> I tried the program:
>
> Médias = matrix(NA, nrow(tab1), ncol(tab1))
> for(i in 1:nrow(tab1)){
> for(j in 1:ncol(tab1)){
> for(k in 1:nrow(tab2)){
> for(l in 1:ncol(tab2)){
> Médias = tab1$i[j]
> }}}}
>
> Médias
>
> but it does't work. I don't know programming.
>
> How can I do this?
>
> Thanks,
From the output above, you would appear to have two data frames. The hint is the column names (V1 ... V5), which is the default for data frames when column names are not otherwise specified. See ?data.frame for more information. You should consider reading An Introduction To R, which will provide a foundational overview of many of these concepts.
In this case, since all values are numeric, the data frames will behave as if they were matrices, which means that we can use R's vectorized approach to adding the two objects together and then just divide by 2. There is not a need to use multiple for() loops.
Thus:
> tab1
V1 V2 V3 V4 V5
1 14.23 1.71 2.43 15.6 127
2 13.20 1.78 2.14 11.2 100
3 13.16 2.36 2.67 18.6 101
4 14.37 1.95 2.50 16.8 113
5 13.24 2.59 2.87 21.0 118
> tab2
V1 V2 V3 V4 V5
1 1.23 1.1 2.3 1.6 17
2 1.20 1.8 2.4 1.2 10
3 1.16 2.6 2.7 1.6 11
4 1.37 1.5 2.0 1.8 13
5 1.24 2.9 2.7 2.0 18
> tab1 + tab2
V1 V2 V3 V4 V5
1 15.46 2.81 4.73 17.2 144
2 14.40 3.58 4.54 12.4 110
3 14.32 4.96 5.37 20.2 112
4 15.74 3.45 4.50 18.6 126
5 14.48 5.49 5.57 23.0 136
> (tab1 + tab2) / 2
V1 V2 V3 V4 V5
1 7.73 1.405 2.365 8.6 72
2 7.20 1.790 2.270 6.2 55
3 7.16 2.480 2.685 10.1 56
4 7.87 1.725 2.250 9.3 63
5 7.24 2.745 2.785 11.5 68
Regards,
Marc Schwartz
More information about the R-help
mailing list