Convert the class to logical of multiple variables in the workspace

29 views Asked by At

I have some logical values being read in as characters from some data, which is being imported in bulk along with other variables, otherwise I would have changed their class at the beginning:

library(tidyverse)

switch_1 <- "TRUE"
switch_2 <- "FALSE"
switch_49 <- "FALSE"
switch_50 <- "TRUE"

I would like to convert these to logical using some kind of elegant loop (as there are many switches)

So far I have tried:

ls() %>%
str_subset("switch") %>%
map(get) %>%
map(as.logical)

Which converts them to the correct format, but doesn't re-assign their values within the workspace.

How can I re-assign their value in the workspace?

> ls() %>% str_subset("switch_") %>% map(get) %>% map(as.logical)
[[1]]
[1] TRUE

[[2]]
[1] FALSE

[[3]]
[1] FALSE

[[4]]
[1] TRUE
1

There are 1 answers

1
PGSA On

Note: this works but I don't think you should do it. It is very prone to messing things up if there is an unexpectedly named object in the global environment.

Change the map() to a custom function which gets the value, makes it as.logical and then assigns it back in the global environment, overwriting its old value/type.

ls() %>%
  str_subset("switch") %>%
  map(\(x) { assign(x, as.logical(get(x)), envir = globalenv()) } )

gives

> switch_1
[1] TRUE

A possibly better approach:

I prefer this, which has the same issue of trawling the global environment at first but at least contains the results:

switches <- mget(ls(pattern = '^switch_')) %>% lapply(as.logical)
switches
$switch_1
[1] TRUE

$switch_2
[1] FALSE

$switch_49
[1] FALSE

$switch_50
[1] TRUE