Home > OS >  How to prevent warning and Inf output when running dplyr mutate statement?
How to prevent warning and Inf output when running dplyr mutate statement?

Time:08-24

I get the output shown below when running the code immediately beneath. Why am I getting Inf in the last column of row 4 of the data frame? It should be 0. Everything else is fine.

> print.data.frame(myDFRender)
  Name Code1 Code2 FixSumIfs FixMinIfs
1    R   0.0     1         0       1.1
2    R   0.0     2         0       1.2
3    B   0.0     1         0       1.1
4    R   0.0     3         0       Inf
5    X   1.1     1         7       1.1
6    X   1.2     2         8       1.2

library(dplyr)

myDF <- 
  data.frame(
    Name = c("R","R","B","R","X","X"),
    Code1 = c(0,0,0,0,1.1,1.2),
    Code2 = c(1,2,1,3,1,2)
  )

myDFRender <- 
  myDF %>% 
  mutate(FixSumIfs = sapply(1:n(), function(x) sum(Code2[1:n()][Code1[1:n()] < Code1[x]]))) %>%
  group_by(Code2) %>%
    mutate(FixMinIfs = min(Code1[Code1 > 0])) %>%
  ungroup()

Warning message:
Problem with mutate() column FixMinIfs.
FixMinIfs = min(Code1[Code1 > 0]).
ℹ no non-missing arguments to min; returning Inf
ℹ The warning occurred in group 3: Code2 = 3.

CodePudding user response:

When Code2 is 3, there is no numbers greater than 0, so Code1[Code1 > 0] returns numeric(0) and min(numeric(0)) triggers the warning. You could add a if statement to rule out the exception.

myDF %>% 
  group_by(Code2) %>%
  mutate(FixMinIfs = if(all(Code1 <= 0)) 0 else min(Code1[Code1 > 0])) %>%
  ungroup()

# # A tibble: 6 × 4
#   Name  Code1 Code2 FixMinIfs
#   <chr> <dbl> <dbl>     <dbl>
# 1 R       0       1       1.1
# 2 R       0       2       1.2
# 3 B       0       1       1.1
# 4 R       0       3       0  
# 5 X       1.1     1       1.1
# 6 X       1.2     2       1.2

CodePudding user response:

Another option

library(collapse)
library(dplyr)
library(tidyr)
myDF %>%
   group_by(Code2) %>% 
   mutate(FixMinIfs = replace_na(fmin(na_if(Code1, 0)), 0)) %>%
   ungroup
# A tibble: 6 × 4
  Name  Code1 Code2 FixMinIfs
  <chr> <dbl> <dbl>     <dbl>
1 R       0       1       1.1
2 R       0       2       1.2
3 B       0       1       1.1
4 R       0       3       0  
5 X       1.1     1       1.1
6 X       1.2     2       1.2
  • Related