Home > Net >  Converting multiple objects from string to numeric in one line r?
Converting multiple objects from string to numeric in one line r?

Time:06-07

I have 3 strings with numbers.

a = "1"
b = "2"
c = "3"

The complicated way of converting a, b and c to numbers with as.numeric() is:

a = as.numeric(a)
b = as.numeric(b)
c = as.numeric(c)

How can I do this in one line?

A bit like this (obviously this doesn't work)

a,b,c = as.numeric(a,b,c)

CodePudding user response:

With the %=% operator from collapse, it is possible

library(collapse)
c('a', 'b', 'c') %=% as.numeric(c(a, b, c))

-output

> a
[1] 1
> b
[1] 2
> c
[1] 3

CodePudding user response:

library(tidyverse)

a = "1"
b = "2"
c = "3"

map_int(c(a, b, c), as.integer)
#> [1] 1 2 3

Created on 2022-06-06 by the reprex package (v2.0.1)

CodePudding user response:

Here is a base R solution, although a bit longer than the others:

list2env(setNames(lapply(c("a","b"), function(x){as.numeric(get(x))}), c("a","b")),.GlobalEnv)

CodePudding user response:

You can store your objects in a list, and then use list2env:

library(tidyverse)
a = "1"
b = "2"
c = "3"

map(lst(a, b, c), as.numeric) %>% 
  list2env(envir = .GlobalEnv)

CodePudding user response:

Another possible solution, using type.convert and base R:

list2env(type.convert(list(a = a, b = b, c = c), as.is = T), .GlobalEnv)

Or using purrr::iwalk and assign:

library(tidyverse)

iwalk(lst(a,b,c), ~ assign(.y, as.numeric(.x), envir = .GlobalEnv))
  • Related