replace_x: Data manipulation.

View source: R/replace_x.R

replace_xR Documentation

Data manipulation.

Description

This is a series of functions designed for a fast coding of replacements both, as internal functions and in workflows dealing with information stored in vectors and data frames. Such functions are especially useful when handling with functional traits stored in taxlist objects.

replace_x() is used to exchange values in vectors. replace_idx() changes values in vectors by matching indices or conditions. The function replace_na() works in the same way as replace_idx() but will only insert values in empty elements (NAs).

The function insert_rows() will add rows and columns at the same time. This function will be used when a new table is appended to another but sharing only part of the columns.

Usage

replace_x(x, old, new)

replace_idx(x, idx1 = x, idx2 = idx1, new)

replace_na(x, idx1, idx2 = idx1, new)

insert_rows(x, y)

Arguments

x

A vector to be modified. In the case of insert_rows(), x is a data frame.

old

A vector with values to be replaced by replace_x() in a vector.

new

A vector containing values to be inserted, either comparing values or using indices.

idx1, idx2

Indices applied for value replacements to match x with new, respectively. If idx2 is not provided, it will be assumed as equivalent to idx1.

y

A data frame including rows (and columns) to be inserted in x.

Value

A vector or data frame with the modified values.

Author(s)

Miguel Alvarez.

Examples

## Replace values in vector
replace_x(x = letters, old = c("b", "p", "f"), new = c("bee", "pork", "fungus"))

## Replace values using indices
replace_idx(x = letters, idx1 = 1:length(letters), idx2 = c(2, 7, 17),
  new = c("second", "seventh", "seventeenth"))

## Replace values if they are NAs
letters[2] <- NA
replace_na(x = letters, idx1 = 1:length(letters), idx2 = c(1:3),
  new = c("alpha", "beta", "zeta"))

## The same applications but this time for functional traits
summary(as.factor(Easplist$life_form))

# Merge annuals
Easplist@taxonTraits$lifeform <- replace_x(x = Easplist@taxonTraits$life_form,
  old = c("obligate_annual", "facultative_annual"), new = c("annual", "annual"))
summary(as.factor(Easplist$lifeform))

# The same effect
Easplist@taxonTraits$lifeform <- replace_idx(x = Easplist@taxonTraits$life_form,
  idx1 = grepl("annual", Easplist@taxonTraits$life_form), idx2 = TRUE,
  new = "annual")
summary(as.factor(Easplist$lifeform))

## Merge data frames including new columns
data(iris)
iris$Species <- paste(iris$Species)
new_iris <- data.frame(Species = rep("humilis", 2), Height = c(15, 20),
  stringsAsFactors = FALSE)
insert_rows(iris, new_iris)

kamapu/taxlist documentation built on Feb. 17, 2024, 8:27 a.m.