[R] first occurrence of a value?

From: Albert-Jan Roskam <fomcl_at_yahoo.com>
Date: Wed, 04 May 2011 04:52:07 -0700 (PDT)


A simple question perhaps, but how do I, within each row, find the first occurence of the number 1 in the df below? I want to use this position to programmatically create the variable 'year'. I'v come up with a solution, but I find it downright ugly. Is there a simpler way? I was hoping for a useful built-in function that I don;t yet know about.

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)) library(gsubfn)
x <- apply(df==1, 1, which)
giveYear <- function(df) { return( as.numeric(gsubfn("^[^0-9]+", "", names(df)[1])) ) }
df$year2 <- sapply(x, giveYear)

Thanks in advance!


All right, but apart from the sanitation, the medicine, education, wine, public order, irrigation, roads, a fresh water system, and public health, what have the Romans ever done for us?

        [[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. Received on Thu 05 May 2011 - 06:25:12 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Thu 05 May 2011 - 07:00:07 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive