简体   繁体   中英

Handling NaN values in custom function summary

I have custom function and I want to replace NaN and Na values with "0.0" what can be a simplest solution.

df <- data.frame(Name = c("asdf","kjhgf","cvbnm","rtyui","cvbnm","jhfd","cvbnm","sdfghj","cvbnm","dfghj","cvbnm"),
                 sale=c(27,28,NA,16,NA,25,NA,14,NA,18,NA),
                 city=c("CA","TX","MN","NY","TX","MT","HU","KL","TX","SA","TX"),
                 Dept = c("HH","MM","NN","MM","AA","VV","MM","HU","JJ","MM","ZZ"))

df$sale = as.numeric(df$sale)
data=df
filter_var= "Name"
filter_val="cvbnm"
Text_var="sale"
Name_of_variable="EXP"
decimal =TRUE
footer=""
Suff="%"

filter_val = ensym(filter_val)
filter_var = rlang::parse_expr(filter_var)
Text_var= ensym(Text_var)
  numdig <- if (decimal == TRUE) {1} else {0}
  dat1<-data %>% select(!!filter_var,!!Text_var) %>% filter(!is.na(!!Text_var))
  dat2<- dat1 %>% filter((!!filter_var == filter_val))
  
  summ_tab1<- dat2 %>% 
    select(!!Text_var)  %>%  summarise(
      q25 = format(round(quantile(!! Text_var,  type=6, probs = seq(0, 1, 0.25), na.rm=TRUE)[2],digits = numdig),nsmall = numdig),
      Median = format(round(quantile(!! Text_var, type=6, probs = seq(0, 1, 0.25), na.rm=TRUE)[3],digits = numdig),nsmall = numdig),
      Average = format(round( mean(!! Text_var, na.rm=TRUE),digits = numdig),nsmall = numdig),
      q75 = format(round(quantile(!! Text_var, type=6, probs = seq(0, 1, 0.25), na.rm=TRUE)[4],digits = numdig) ,nsmall = numdig),
      N = sum(!is.na(!!Text_var)))
  summ_tab1

summ_tab1[2,](is.nan(summ_tab1[2,0])) <- "0.0"

I have tried this but doesn't work

这是你想要的吗?

summ_tab1[1, 1:4] <- "0.0"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM