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
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 whichgets the value, makes itas.logicaland thenassigns it back in the global environment, overwriting its old value/type.gives
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: