[R] Average of a variable against another.

David Winsemius dwinsemius at comcast.net
Fri Feb 12 03:30:59 CET 2010


On Feb 11, 2010, at 7:32 PM, Keeeeeeee wrote:

>
> Dear helpers,
>
> FYI, I am a beginner of R, just have dealt with MATLAB or JAVA.
>
> I want to know how to solve one problem given 4 variables: year_1,  
> year_2,
> tall_1, tall_2.
> The tall_1 is measured at year_1 and tall_2 at year_2.
> The tall has grown up such as uniformly 1 cm/yr.
>
> The data is like
>
> year_1 year_2 tall_1 tall_2
> 2007    2010    12    15
> 1999    2009    6    16
> 2003    2005    11    13
> 2002    2009    3    10
>    .    .    .    .    .
>    .    .    .    .    .
>    .    .    .    .    .
>    .    .    .    .    .
>
> So I need to get the average tall of the plant against year, for all  
> the
> years of available data.
For an individual plant, Wouldn't this just be (tall_2 + tall_1)/2?

(Or if you wanted to do it the hard way then use seq and divide by  
number of years:)

 > dfp <- rd.txt("year_1 year_2 tall_1 tall_2
+ 2007    2010    12    15
+ 1999    2009    6    16
+ 2003    2005    11    13
+ 2002    2009    3    10")

 > dfp$plant.avg <- apply(dfp, 1, function(x) sum(seq(x[3], x[4]) ) /  
(x[2]-x[1]+1) )
 > dfp
   year_1 year_2 tall_1 tall_2 plant.avg
1   2007   2010     12     15      13.5
2   1999   2009      6     16      11.0
3   2003   2005     11     13      12.0
4   2002   2009      3     10       6.5

 > dfp$plant.avg2 <- apply(dfp, 1, function(x) (x[3]+ x[4] ) / 2 )
 > dfp
   year_1 year_2 tall_1 tall_2 plant.avg plant.avg2
1   2007   2010     12     15      13.5       13.5
2   1999   2009      6     16      11.0       11.0
3   2003   2005     11     13      12.0       12.0
4   2002   2009      3     10       6.5        6.5

I don't think you need to create the display below if you want to  
answer the question posed. And if this happens to be homework, be sure  
that I get credit.

-- 
David

> The year_1 and year_2 are recorded so that a plant is alive if the  
> year of a
> question is equal to or grater than the year_1 and equal to and less  
> than
> the year_2.
>
> For example,
> 1999    2000    2001    2002    2003    2004    2005    2006     
> 2007    2008
> 2009    2010
>   6          7          8          9        10        11        12
> 13        14       15      16
>                                       3         4           
> 5          6
> 7         8        9       10
>                                                 11        12        13
>
> 12       13      14        15
>
> avg
>  6        7            8         6         25/3 ...etc.
>
> Since the amount of the data is too huge, I need to use appropriate
> functions and algorithm but I am
> not good at programming R.
>
> I wish you help me out from this hell problem please.
>
> Thanks,
> Keeeeeeee
>
> -- 


David Winsemius, MD
Heritage Laboratories
West Hartford, CT



More information about the R-help mailing list