replaceNAs: Replace NAs in a data.table or data.frame column, or in a...

replaceNAs,data.frame-methodR Documentation

Replace NAs in a data.table or data.frame column, or in a vector

Description

This function replaces NAs in one or more data.table, data.frame, or matrix columns, or in vectors, with a user-defined value.

Usage

## S4 method for signature 'data.frame'
replaceNAs(x, replace, cols = NULL)

## S4 method for signature 'matrix'
replaceNAs(x, replace, cols = NULL)

## S4 method for signature 'data.table'
replaceNAs(x, replace, cols = NULL)

## S4 method for signature 'numeric'
replaceNAs(x, replace)

## S4 method for signature 'integer'
replaceNAs(x, replace)

## S4 method for signature 'logical'
replaceNAs(x, replace)

## S4 method for signature 'character'
replaceNAs(x, replace)

Arguments

x

A data.table or data.frame or matrix, or a vector of numeric, integer, logical, or character values.

replace

A value of any atomic class (numeric, integer, character, Date, etc.): Value to to replace NAs.

cols

NULL, character, numeric, integer, or logical vector: Indicates columns for which to replace NAs. If NULL, then all columns will have NAs replaced. If a character, this is the column name(s). If numeric or integer, this is the columns' indices. If logical, columns with TRUE have NAs replaced. If a logical vector has fewer than the total number of columns, it will be recycled.

Value

A data.table, data.frame, matrix, or vector.

Examples


library(data.table)

dt <- data.table(
   x = 1:10,
   y = letters[1:10],
   z = rnorm(10)
)

# make some values NA
dt[x == 4 | x == 8, y := NA_character_]
dt

# Replace NAs:
replaceNAs(dt, replace = -99, cols = "y")
dt

# Drop rows:
dropped <- dropRows(dt, 8:10)
dropped

# NB May not print... in that case, use:
print(dropped)

# We can also use replaceNAs() on vectors:
y <- 1:10
y[c(2, 10)] <- NA
replaceNAs(y, -99)

# Same as:
y <- 1:10
y[c(2, 10)] <- NA
y[is.na(y)] <- -99

adamlilith/fasterRaster documentation built on Dec. 21, 2024, 2:04 a.m.