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

PIKAL Petr petr.pikal at precheza.cz
Mon Apr 8 15:34:26 CEST 2013


Hi

another option is to use na.locf from zoo, based on assumption that each zero has to be replaced with previous nonzero value.

dat[dat==0]<-NA
library(zoo)

dat$state<-na.locf(dat$state)
dat$country<-na.locf(dat$country)

> dat
                 val state country
1 -0.543116777672352    TN   India
2 -0.178662085411817    TN   India
3  -2.30107974754641    TN   India
4   0.24385819927209    AP   India
5  -1.42584380820816    AP   India
6  -1.17248639661816    AP   India

Petr


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of arun
> Sent: Monday, April 08, 2013 3:10 PM
> To: R help
> Subject: [R] How to replace zero with the character value- need help
> 
> Hi,
> 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[1]
> #or
> 
> #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})) #or
> #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)
>  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
> 
> 
> A.K.
> 
> 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
> 
> 
> ______________________________________________
> 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