Search
 
SCRIPT & CODE EXAMPLE
 

R

convert na to 0 in r

# Base R: 
baseR.sbst.rssgn   <- function(x) { x[is.na(x)] <- 0; x }
baseR.replace      <- function(x) { replace(x, is.na(x), 0) }
baseR.for          <- function(x) { for(j in 1:ncol(x))
    x[[j]][is.na(x[[j]])] = 0 }

# tidyverse
## dplyr
dplyr_if_else      <- function(x) { mutate_all(x, ~if_else(is.na(.), 0, .)) }
dplyr_coalesce     <- function(x) { mutate_all(x, ~coalesce(., 0)) }

## tidyr
tidyr_replace_na   <- function(x) { replace_na(x, as.list(setNames(rep(0, 10), as.list(c(paste0("var", 1:10)))))) }

## hybrid 
hybrd.ifelse     <- function(x) { mutate_all(x, ~ifelse(is.na(.), 0, .)) }
hybrd.replace_na <- function(x) { mutate_all(x, ~replace_na(., 0)) }
hybrd.replace    <- function(x) { mutate_all(x, ~replace(., is.na(.), 0)) }
hybrd.rplc_at.idx<- function(x) { mutate_at(x, c(1:10), ~replace(., is.na(.), 0)) }
hybrd.rplc_at.nse<- function(x) { mutate_at(x, vars(var1:var10), ~replace(., is.na(.), 0)) }
hybrd.rplc_at.stw<- function(x) { mutate_at(x, vars(starts_with("var")), ~replace(., is.na(.), 0)) }
hybrd.rplc_at.ctn<- function(x) { mutate_at(x, vars(contains("var")), ~replace(., is.na(.), 0)) }
hybrd.rplc_at.mtc<- function(x) { mutate_at(x, vars(matches("d+")), ~replace(., is.na(.), 0)) }
hybrd.rplc_if    <- function(x) { mutate_if(x, is.numeric, ~replace(., is.na(.), 0)) }

# data.table   
library(data.table)
DT.for.set.nms   <- function(x) { for (j in names(x))
    set(x,which(is.na(x[[j]])),j,0) }
DT.for.set.sqln  <- function(x) { for (j in seq_len(ncol(x)))
    set(x,which(is.na(x[[j]])),j,0) }
DT.nafill        <- function(x) { nafill(df, fill=0)}
DT.setnafill     <- function(x) { setnafill(df, fill=0)}
Comment

PREVIOUS NEXT
Code Example
R :: r suppress package loading messages 
R :: r na if 
R :: r replace space with 
R :: r matrix 
R :: replace any NA in a data frame in r 
R :: what is a vector in r 
R :: how to create for loop through columns and count non na cells by group in r 
R :: knn in r 
R :: reorder columns in r 
R :: change the y ticks in r plot 
R :: how to iterate through a list in r 
R :: select a value in a data frame R 
R :: How to extract NA´s from a column? in R 
R :: convert country code to country name in r 
R :: link excel to r 
R :: select last child with class in r 
R :: colorblind-friendly palette in r 
R :: Extract the text of all list elements in r from html 
R :: XLConnect 
R :: legend in r 
Rust :: rust string to char array 
Rust :: rust request get headers 
Rust :: rustlang string 
Rust :: rust vec to array 
Rust :: how to make map in rust language 
Rust :: armanriazi•rust•error•[E0308]: mismatched types expected integer, found floating-point number 
Rust :: rust BMI 
Rust :: armanriazi•rust•error•E0277•`Point<{integer}, {float}` cannot be formatted using ` 
Rust :: rust init vector with range 
Rust :: rust•armanriazi•refactor 
ADD CONTENT
Topic
Content
Source link
Name
8+2 =