[R] Lowest year among several variables

Sarah Goslee sarah.goslee at gmail.com
Tue May 8 21:59:50 CEST 2012


It's neater if you use dput() to give your data rather than just
copying it into the email, but anyway:

> testdata <- read.table("clipboard", header=TRUE)
> apply(testdata, 1, function(x)if(all(x == 0)) {0} else {min(x[x > 0])})
[1] 80 76 86  0

Sarah

On Tue, May 8, 2012 at 3:50 PM, Jeff <r at jp.pair.com> wrote:
>
> ...still new to R and trying to figure this one out.
>
> I have a number of variables x, y, z, etc. in a data frame.
>
> Each contains a 2 digit year (e.g., 80, 81, 82) representing the first year
> that something occurred. Each variable represents a different type of event.
>
> If the event did not occur at all, the variable has the value 0 (zero).
>
> I need to create a new variable having the value of the earliest year among
> the set of variables.
>
> If none of the events occurred (all variables = 0), then the new variable
> should also be zero.
>
> e.g.,
>
> Original
> x    y   z
> 80 82 83
> 85  76  90
> 90  0   86
> 0   0   0
>
>
> New variable
> 80
> 76
> 86
> 0
>


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list