r - Filling in NAs with corresponding row values in another column -


i using rstudio. have simple data frame looks following:

 df <-   id  tad  tnom   1    0    0   1    0.3  na   1    0.6  0.5   1    1    na 

i want code fills in na tnom corresponding row value in tad column.

the result should be:

 df <-  id  tad  tnom   1    0    0   1    0.3  0.3   1    0.6  0.5   1    1    1 

example:

df <- data.frame(id=c(1,1,1,1), tad=c(0,0.3,0.6,1), tnom=c(0,na,0.5,na)) df #   id tad tnom # 1  1 0.0  0.0 # 2  1 0.3   na # 3  1 0.6  0.5 # 4  1 1.0   na 

using ifelse(condition,true,false)

df$tnom<-ifelse(is.na(df$tnom),df$tad,df$tnom) 

or using with(data, expression)

df$tnom<-with(df,ifelse(is.na(tnom),tad,tnom)) 

or reassigning values based on is.na()

df$tnom[is.na(df$tnom)] <- df$tad[is.na(df$tnom)] 

all 3 gives:

df #   id tad tnom # 1  1 0.0  0.0 # 2  1 0.3  0.3 # 3  1 0.6  0.5 # 4  1 1.0  1.0 

Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -