This should do what you want -- not sure what happens after the 4th less than 5.
> a <- rep(c(3,5,7), 4)
> b <- rep(c(NA,1,2), 4)
> df <- data.frame(a,b)
> # determine which ones are < 5 and count the occurances
> less.5 <- cumsum(df$a < 5)
> # create new value
> df$c <- ifelse(df$a < 5, (less.5 + 1) %/% 2, df$b)
> df
a b c
1 3 NA 1
2 5 1 1
3 7 2 2
4 3 NA 1
5 5 1 1
6 7 2 2
7 3 NA 2
8 5 1 1
9 7 2 2
10 3 NA 2
11 5 1 1
12 7 2 2
On Sat, May 3, 2008 at 3:43 PM, Greg Blevins <gregblev at gmail.com>
wrote:> Hello, R-helpers.
>
> I have a data frame below called df. I want to add a variable c, based on
> the following logic:
>
> if df$a < 5 then the first two times this condition is met place a 1 in
c,
> the next two times this condition is met place a 2 in c and when the
> condition is not met let c equal df$b. The result would look like, dfnew,
> shown below.
>
>
> a <- rep(c(3,5,7), 4)
> b <- rep(c(NA,1,2), 4)
> df <- data.frame(a,b)
>
> > df
> a b
> 1 3 NA
> 2 5 1
> 3 7 2
> 4 3 NA
> 5 5 1
> 6 7 2
> 7 3 NA
> 8 5 1
> 9 7 2
> 10 3 NA
> 11 5 1
> 12 7 2
>
> c <- c(1 , 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 2)
> dfnew <- data.frame(a, b,c)
> > dfnew
> a b c
> 1 3 NA 1
> 2 5 1 1
> 3 7 2 2
> 4 3 NA 1
> 5 5 1 1
> 6 7 2 2
> 7 3 NA 2
> 8 5 1 1
> 9 7 2 2
> 10 3 NA 2
> 11 5 1 1
> 12 7 2 2
>
> Thanks
> Greg
> R 2.7 XP
>
> --
> Gregory L. Blevins
> Office 952 944-5743
> Cell 612 251 0232
> gregblev at gmail.com
>
> [[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.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem you are trying to solve?