[R] conditional value assignment

penguins catrsw at bas.ac.uk
Mon Oct 22 00:53:43 CEST 2012


I am trying to assign values to records based conditionally on other records
within a dataframe. For example, in the following dataframe the "NA" value
in dat$age would be replaced if the age status for that individual and
specific year can be found in another record. Ideally this would then also
assign the same age status if the individual is recorded in a later year.

id<-c(1,1,1,1,2,2,2,2,2, 3,3,3, 4,4)         
year<-c(1,1,1,2, 2,2,3,2,2, 2,3,4, 8,8)          
age<-c("Adult","NA","NA","NA", "Adult","NA","NA","NA", "Adult",
"NA","Adult","NA", "NA","Adult")    

I am attempting to transform the age variable to;

I have used the following code to cross-reference the age data across
records of the same year but am having trouble getting this work. I am also
unsure how to cross-reference this to assign age status to records of the
same individual recorded in later years.


for (i in 1:nrow(namer)) {
dat$age[dat$id == namer[i,1] & dat$year== namer[i,2]] <- "Adult"

Any help would be gratefully recieved,


View this message in context: http://r.789695.n4.nabble.com/conditional-value-assignment-tp4646945.html
Sent from the R help mailing list archive at Nabble.com.

More information about the R-help mailing list