Skip to contents

Replace all values of x to value of y in data frames or matrices.

Usage

replace_xy(data, x, y)

# S3 method for class 'data.frame'
replace_xy(data, x, y)

# S3 method for class 'nest_df'
replace_xy(data, x, y)

# S3 method for class 'group_df'
replace_xy(data, x, y)

# S3 method for class 'matrix'
replace_xy(data, x, y)

Arguments

data

A data frame or matrix.

x

Value you wish be replaced. A vector of length 1.

y

Value you wish to insert. A vector of length 1.

Value

data.frame or matrix

Details

Data frames

Be aware of R's coercion rules when using this function on a data frame of mixed type. Any column that matches the type of 'x' will be a candidate for having it's values replaced with 'y'. This means you will need to use 'x = NA_integer_' to replace NA's in integer columns, 'x = NA_real_' to replace NA's in numeric columns, 'x = NA_character_' to replace NA's in character columns, and 'x = NA' to replace NA's in logical columns.

If 'y' is of a different type than 'x', then the candidate column will be coerced to type 'y' or 'y' will be coerced to type 'x'. In general, if 'x' is located in any column on the left of the following list, and 'y' is on the right, then the whole column where 'x' is located will be coerced to the type of 'y'. Similarly, if 'x' is on the right and 'y' is on the left, then 'y' will be coerced to type 'x'.

logical -> integer -> numeric -> complex -> character.

Some additional notes are in the table below:

Column TypeNotes
NumericSupported
IntegerSupported
CharacterSupported
LogicalSupported
Factor'y' only replaces 'x' if 'y' is a valid factor level in the factor column.
ListA list 'y' only replaces non-list (and not factor) 'x'. Errors for 'x' = 'Inf'.
POSIXctError
POSIXltError
DateError

Matrices

Matrices are always of a single data type. This means type checking is not needed for 'x' (It will select any value in the matrix that a coerced 'x' will match), but types will be checked for 'y'. If the type of 'y' does not match the matrix, then an error will be returned.

Examples

#----------------------------------------------------------------------------
# replace_xy() examples.
#----------------------------------------------------------------------------
library(bkmisc)

d <- data.frame(
var1 = c(Inf, 2, 3),
var2 = c(4, 5, 6)
)
d
#>   var1 var2
#> 1  Inf    4
#> 2    2    5
#> 3    3    6
replace_xy(data = d, x = Inf, y = NA)
#>   var1 var2
#> 1   NA    4
#> 2    2    5
#> 3    3    6

m <- matrix(
c(NA, 2, 3, 4, 5, 6),
nrow = 3,
ncol = 2
)
m
#>      [,1] [,2]
#> [1,]   NA    4
#> [2,]    2    5
#> [3,]    3    6
replace_xy(data = m, x = NA, y = 0)
#>      [,1] [,2]
#> [1,]    0    4
#> [2,]    2    5
#> [3,]    3    6