na.replace: Replace Missing Values

Description Usage Arguments Details Value See Also Examples

View source: R/na.replace.R

Description

Replaces NA values with explicit values.

Usage

1
2
3

Arguments

x

vector in which NA values are to be replaced.

.na

scalar, length(x)-vector or function used to replace NA. See #Details.

...

additional arguments passed to .na when it is a function.

Details

na.replace replaces missing values in x by .na if possible.

In R, replacement of values can cause a change in the class/type of an object. This is not often desired. na.replace is class/type-safe and length-safe. It replaces missing values without changing the x's class or length regardless of the value provided by .na.

Param: x

If x is categorical (e.g. character or factor), .na is optional. The default is "(NA)" and can be set with options( NA_explicit_ = new_value ). It can also be referenced directly with NA_explicit_.

If x is a factor, unique values of .na not in already present in levels(x) will be added. They are appended silently unless getOption('verbose')==TRUE in which a message reports the added levels.

Param: .na

.na can be either a scalar, vector or function.

If a scalar, each missing value of x is replaced by na.

If a vector, .na must have length(x). Missing values ofxare replaced by corresponding elements of.na. Recycling values of.nais not allowed. An error will be thrown in the event thatlength(.na)is not1orlength(x).

If a function, x is transformed by .na' with:

1
     .na(x, ...)

then preceding with normal operations.

na.explicit is an alias for na.replace that uses NA_explicit_ for '.na“; it returns x unchanged if it cannot change the value.

Value

A vector with the class and length of x. NAs in x will be replaced by .na. .na is coerced as necessary.

See Also

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  # Integers and numerics
  na.replace( c(1,NA,3,NA), 2 )    # 1 2 3 2   
  na.replace( c(1,NA,3,NA), 1:4 )  # 1 2 3 4

  # This produces an error because it would change the type
  ## Not run: 
  na.replace( c(1,NA,3,NA), letters[1:4] )  # "1" "b" "3" "d"
  
## End(Not run)
  
  # Characters 
  lets <- letters[1:5]
  lets[ c(2,4) ] <- NA
  na.replace(lets)  # replace with NA_explicit_

  # Factors 
  fct <- as.factor( c( NA, letters[2:4], NA) )
  fct
  na.replace(fct, "z")  # z b c d z  -- level z added
  na.replace(fct, letters[1:5] )
  na.replace(fct)
     
 ## Not run: 
   na.replace( rep(NA,3), rep(NA,3) )
 
## End(Not run)
     

na.tools documentation built on June 26, 2018, 5:02 p.m.