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
[EMAIL PROTECTED]

        [[alternative HTML version deleted]]

______________________________________________
R-help@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.

Reply via email to