'How to evaluate a character string when numeric is needed in R?

I want to change a numeric into a factor, but my factor level is given as a character string while the function factor needs a numeric. How do I convert it into a numeric or evaluate the character string? Example:

given:

a = c(0,1,1,1,0,1,0)

lev = 'c(0,1)' 

lab = c('firstlev','secondlev') # this is irrelevant to question.

wanted:

factor(a,levels = lev labels = lab)

I could write the levels explicitly, but I have a big loop and am reading the factor levels automatically from another file. I tried quo, !!, eval and friends, but I am totally lost as to what is the right way to do and even what I should be looking for, conversion from string to numeric, or for a type of evaluation of a string.



Solution 1:[1]

How about this:

a = c(0,1,1,1,0,1,0)

lev = 'c(0,1)' 

lab = c('firstlev','secondlev') # this is irrelevant to question.

factor(a,levels = eval(parse(text=lev)), labels = lab)
#> [1] firstlev  secondlev secondlev secondlev firstlev  secondlev firstlev 
#> Levels: firstlev secondlev

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DaveArmstrong