[R] conditional value assignment
Rui Barradas
ruipbarradas at sapo.pt
Mon Oct 22 07:29:44 CEST 2012
Hello,
First of all, two notes on the way you create your data.frame
1. Use age <- c("Adult", NA, ...etc...) _without_ quotes around NA. If
you use quotes it will seen as a character, not as the value NA.
2. Do not cbind and then coerce to data.frame, use data.frame only.
So the data and an answer to your question could be
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")
dat <- data.frame(id, year, age)
fun <- function(x){
for(i in which(!is.na(x$age)))
x$age[x$year >= x$year[i]] <- x$age[i]
x
}
do.call(rbind, lapply(split(dat, dat$id), fun))
Also, I coudn't understand that 'namer' stuff. But you repeat the
mistake cbind/data.frame.
Hope this helps,
Rui Barradas
Em 21-10-2012 23:53, penguins escreveu:
> Hi,
>
> 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")
> dat<-cbind(id,year,age)
> dat<-data.frame(dat)
>
> I am attempting to transform the age variable to;
> "Adult","Adult","Adult","Adult",
> "Adult","Adult","Adult","Adult","Adult","NA","Adult","Adult","Adult","Adult"
>
> 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.
>
> id<-unique(dat$id)
> year<-c(1,2,3,8)
> namer<-cbind(pit,season)
> namer<-data.frame(namer)
>
> 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,
>
> Thanks
>
>
>
>
> --
> 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.
>
> ______________________________________________
> 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.
More information about the R-help
mailing list