[R] How to replace zero with the character value- need help

arun smartpink111 at yahoo.com
Mon Apr 8 15:10:00 CEST 2013

Not sure if you have only one "country" or not. 

Try this:
dat<- data.frame(val,state,country,stringsAsFactors=FALSE)

#dat$country[dat$country==0]<- dat$country[dat$country!=0]

 res<-do.call(rbind,lapply(split(dat,cumsum(grepl("[A-Za-z]",dat$state))),function(x) {x$state[x$state==0]<- x$state[1];x}))
#res<- do.call(rbind,lapply(split(dat,cumsum(grepl("[A-Za-z]",dat$state))),function(x) {x$state[x$state==0]<- x$state[x$state!=0];x}))
 row.names(res)<- 1:nrow(res)
#          val state country
#1  1.50643668    TN   India
#2 -0.88024059    TN   India
#3  0.35025608    TN   India
#4 -0.08874850    AP   India
#5 -1.69222182    AP   India
#6  0.09479274    AP   India


Respected Sir/Madam 

The dataset I have,  given below. 

set.seed <- (1) 
val <- rnorm(6) 
state <- c("TN",0,0,"AP",0,0) 
country <- c("India",0,0,0,0,0) 
dat <- as.data.frame(cbind(val,state,country)) 

The dataset I need is given 

state1 <- c("TN","TN","TN","AP","AP","AP") 
country1 <- c("India","India","India","India","India","India") 
dat1 <- as.data.frame(cbind(val,state1,country1)) 

Please help me or direct me to fill the zeros with the appropriate character values. 
Thanking you in advance 

More information about the R-help mailing list