I have vectors A
, B
, and C
which are of class character. I want them to be numeric, and rather than writing this a bunch of times:
A <- as.numeric(A)
I'd much rather write one expression that converts them all. How can I do that?
I have vectors A
, B
, and C
which are of class character. I want them to be numeric, and rather than writing this a bunch of times:
A <- as.numeric(A)
I'd much rather write one expression that converts them all. How can I do that?
Well the obvious way is to put them into a list and *apply
the conversion:
result = sapply(list(A, B, C), as.numeric, simplify = FALSE)
But unpacking the results again gets messy:
A = result$A
# … etc.
but you can just use result
as its own environment-like object if you just need to access the objects temporarily:
local({
do_something_with(A)
and_also(B, C)
}, result)
Alternatively, the following code also works but it’s a bit dodgy (list application with side effects always is, and assigning into a parent scope is doubly so):
invisible(list2env(lapply(mget(c('A', 'B', 'C')), as.numeric), environment())
I advise against this.