Skip to content

first occurrence of a value?

4 messages · Dimitris Rizopoulos, Patrick Breheny, Albert-Jan Roskam

#
another approach is:

df <- data.frame(j1999 = c(0,0,0,0,1,0), j2000 = c(NA,1,1,1,0,0),
     j2001 = c(1,0,1,0,0,0))

years <- as.numeric(gsub("^[^0-9]+", "", names(df)))
ind <- apply(sapply(df, "==", 1), 1, function (x) which(x)[1])
df$year <- years[ind]


I hope it helps.

Best,
Dimitris
On 5/4/2011 1:52 PM, Albert-Jan Roskam wrote:

  
    
#
You may want to look into the function 'match', which finds the first 
occurrence of a value.  In your example,

df <- data.frame(j1999=c(0,0,0,0,1,0), j2000=c(NA, 1, 1, 1, 0, 0), 
j2001=c(1, 0,
1, 0, 0, 0), year=c(2001, 2000, 2000, 2000, 1999, NA))

apply(df,1,match,x=1)

[1]  3  2  2  2  1 NA

_______________________
Patrick Breheny
Assistant Professor
Department of Biostatistics
Department of Statistics
University of Kentucky
On 05/04/2011 07:52 AM, Albert-Jan Roskam wrote: