'ifelse and replacing a single value

As training, I'm trying to reproduce a data transformation on this db ( https://studysites.uk.sagepub.com/dsur/study/DSUR%20Data%20Files/Chapter%205/DownloadFestival(No%20Outlier).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)
r


Solution 1:[1]

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

Solution 2:[2]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Nick Camarda