Home > Back-end >  ifelse and replacing a single value
ifelse and replacing a single value

Time:04-16

As training, I'm trying to reproduce a data transformation on this db ( https://studysites.uk.sagepub.com/dsur/study/DSUR Data Files/Chapter 5/DownloadFestival(No Outlier).dat )

dlf$day2<-as.numeric(dlf$day2)


dlf$recday2b<- 1/(dlf$day2   1)
dlf$recday2b[is.na(dlf$recday2b)] <-0

using ifelse, but I'm unable to make ifelse replace NA values with 0s.

I tried these without success:

dlf$recday2b<-ifelse(is.na(dlf$day2), replace(dlf$day2, NA, 0), 1/(dlf$day2   1))

dlf$recday2b<-ifelse(dlf$day2!="", 1/(dlf$day2   1), dlf$day2==0)

CodePudding user response:

If I understand correctly you don't have a problem to create the new variable recday2b but you just want to change when the recday2b is NA to 0

Using ifelse you could try

dlf$recday2b <-ifelse(is.na(dlf$recday2b), 0, dlf$recday2b) 
dlf$recday2b <- ifelse(is.na(dlf$day2), 0, dlf$recday2b) #same result

Otherwise you also have the replace_na() function that takes a dataframe or vector as an argument

CodePudding user response:

You should try something like this with replace_na using the argument replace = list("variable_name" = 0), like so:

library(tidyverse)
dlf <- tribble(~A, ~recday2b, 
        1, NA,
        2, 0.5, 
        1, 0.2, 
        3, NA); dlf
#> # A tibble: 4 × 2
#>       A recday2b
#>   <dbl>    <dbl>
#> 1     1     NA  
#> 2     2      0.5
#> 3     1      0.2
#> 4     3     NA

dlf %>% 
  replace_na(replace = list("recday2b" = 0))
#> # A tibble: 4 × 2
#>       A recday2b
#>   <dbl>    <dbl>
#> 1     1      0  
#> 2     2      0.5
#> 3     1      0.2
#> 4     3      0

Created on 2022-04-15 by the reprex package (v2.0.1)

  •  Tags:  
  • r
  • Related