On Thu, 1 Jul 2010, LogLord wrote:
As requested, here is some example data:
a=c("x","y","z")
b=c(1,5,8)
c=c(200010,535388,19929)
data=data.frame(a,b,c)
d=c("cat1","cat2","cat3")
b1=c(1,5,8)
c_start=c(200000,500000,600000)
c_stop=c(201000,550000,700000)
category=data.frame(d,b1,c_start,c_stop)
I want to add a variable into data, which assigns in this case to "x"
"cat1", "y" "cat2" and leaves "z" unassigned. So first it should test if b =
b1 for each row and if this is true it should test if c >= c_start and <=
c_stop. If this is all true the value of d should be transfered into the new
variable.
Like this?
data$new.var <- category$d
is.na( data$new.var ) <- with(data, b != category$b1 | c < category$c_start |
c> category$c_stop )
data
a b c new.var
1 x 1 200010 cat1
2 y 5 535388 cat2
3 z 8 19929 <NA>
You may want to read up on
?match
and
?merge
in case the rows of data and those of category are not in
one-to-one correspondence.
Charles C. Berry (858) 534-2098
Dept of Family/Preventive Medicine
E mailto:cbe...@tajo.ucsd.edu UC San Diego
http://famprevmed.ucsd.edu/faculty/cberry/ La Jolla, San Diego 92093-0901
______________________________________________
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.