Home > Software design >  How to Replace Nan and Inf with a specific Value (IFERROR Function in Excel) using Pipe function in
How to Replace Nan and Inf with a specific Value (IFERROR Function in Excel) using Pipe function in

Time:12-15

I am creating a columns using math formulae's in R, and I am coming across cases which has NaN and Inf after the calculation. All these columns are done using pipe function (%>%). But unfortunately I am running into issue with replacing the Nan with Inf.

Can someone suggest a way to do an do this using Pipe Function. Is this possible to be done in Pipe Function. The code I was writing is given below. And I got stuck here.

X <- X %>% 
  mutate(X1_Value = (X1*Y)) %>% 
  mutate(X2_Value = (X2*Y)) %>% 
  mutate(Check1 = ((X1_Value -X2_Value)/X1_Value )) %>% 
  mutate(Check2 = abs((X1_Value -X2_Value)/X1_Value ))

I have selected a few columns which include the data. Using this code:

X1 <- X %>% 
select(Key,Check3)

I have selected a small reproduceable data from my main data set. This is the dput:

structure(list(Key = c("XYZ-1", "XYZ-2", "XYZ-3", "XYZ-4", "XYZ-5"), Check3 = c(NaN, NaN, Inf, 2.5, -1.7)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))

Can someone try this excel iferror function on that Check3 column in the above data set so that I can replace the Nan and Inf to 0 or 1. Based on situations.

CodePudding user response:

I would recommend to use this as solution.

X1 <- X1 %>%
  mutate(Check4 = ifelse(Check3 == "NaN" ,1,Check3)) %>%
  mutate(Check4 = ifelse(Check4 == "Inf",1,Check3)

I believe this should do it. This covers the idea which you are looking for.

Do have a look and let me know if you got it.

CodePudding user response:

library(tidyverse)
X1 <- X1 %>% 
  mutate(Check3 = ifelse(is.na(Check3)==T|
                           Check3==Inf,0,Check3)
         
  )

library(tidyverse)
X <- X %>% 
  mutate(X1_Value = (X1*Y),
         X2_Value = (X2*Y)) %>% 
  mutate(Check1 = ifelse(is.na((X1_Value -X2_Value)/X1_Value )==T,Inf,
                         (X1_Value -X2_Value)/X1_Value ),
         Check2 = ifelse(is.na(abs((X1_Value -X2_Value)/X1_Value ))==T,
                         Inf,abs((X1_Value -X2_Value)/X1_Value ))
         )



  • Related