apply_paste
NoteAdded in development version
What it does
Checks for usage of apply(x, 1, paste, collapse = ...) to paste together the columns of each row.
Why is this bad?
apply() coerces its input to a matrix and calls paste() once per row, which is slow. Since paste() is vectorized, the same result can be obtained in a single call with do.call(paste, c(x, sep = ...)), which is both faster and clearer.
The automated fix is marked unsafe because the result of do.call(paste, c(x, sep = ...)) depends on the type and content of x. It can differ from the original call when:
xis a matrix:c(x, sep = ...)is not a list, sodo.call()errors.xis adata.framemixing character and non-character columns:apply()converts it withas.matrix(), which pads numbers and logicals to a common width (e.g." 1_x"instead of"1_x").xhas a column namedsep,collapse, orrecycle0: it is matched to the argument ofpaste()with the same name, which either errors or changes the output.xhas non-automatic row names:apply()uses them to name the output,do.call(paste, ...)does not.collapseis a variable that evaluates toNULL:apply()doesn’t collapse rows, whilec()dropssep = NULLsopaste()uses its defaultsep = " ".
Example
apply(df[, c("x", "y")], 1, paste, collapse = "_")Use instead:
do.call(paste, c(df[, c("x", "y")], sep = "_"))References
See ?do.call and ?paste