replace_along: Replace Values in a Vector if condition apply

Description Usage Arguments Value Note Examples

Description

Replaces the values in x with indices determined by condition by those given in values.

Usage

1
replace_along(x, condition, values, y = x)

Arguments

x

base vector, elements of which are to be replaced

condition

action depends on the type:

  • logical or numeric — condition is an index vector

  • character — condition is a vector of regex patterns; replace if any pattern matches

  • expression — evaluated first, then used according to type

  • other — invoked as a function, then result used as a index vector

values

vector of replacement variables or scalar, reused

y

vector tested for condition

Value

Vector x with the values replaced according to condition

Note

Usage of values here differs from that in the base replace. In replace elements of x matching index are replaced by elements of values starting with the first on: x[idx] <- values. In replace_along corresponding elements of the values vector are copied: x[idx] <- values[idx].

If values is NULL, corresponding elements of x are dropped

x is unchanged: remember to assign the result

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# Replace summer months
replace_along(month.name, 6:8, "-")

# Replace missing values
x <- c("one", NA, "three")
replace_along(x, is.na, "-")

# Replace month name with abbreviation if name ends with "ry" or "er"
replace_along(month.name, c("ry$", "er$"), month.abb)

# Generate random pluses and minuses
replace_along("+", rnorm(20) < 0, "-")

# Replace month name with abbreviation if a name is longer than 5 characters.
# All variants below achieve the same result.
replace_along(month.name, nchar(month.name) > 5, month.abb)
replace_along(month.name, expression(nchar(x) > 5), month.abb)
replace_along(month.name, expression(y > 5), month.abb, nchar(month.name))
replace_along(month.name, function(n) n > 5, month.abb, nchar(month.name))

avidclam/amxtra documentation built on May 17, 2019, 12:01 p.m.