Search code examples
roperatorscoercion

Converting a text import of a range in format 1:5 from character with : operator to a numeric string/value for use in a function


I am importing a key in which each row is an argument setting for a function I have programmed. The goal is to batch test my function by producing outputs for all sets of arguments. That's not terribly important. What is important is that I import a column that contains in each row a value for a range. For instance, "1:5" is meant to be entered into an argument as the value 1:5. I try to coerce using as.numeric("1:5"), but R is not happy with this. Is there a way to coerce this to the string c(1,2,3,4,5) from the character value "1:5"


Solution

  • Your text is valid code, so you can eval(parse it

    dat$parsed <- lapply(dat$key, function(x) eval(parse(text=x)))
    #   key           parsed
    # 1 1:5    1, 2, 3, 4, 5
    # 2 1:6 1, 2, 3, 4, 5, 6
    # 3 1:4       1, 2, 3, 4
    

    Data

    dat <- read.table(text="key
    1:5
    1:6
    1:4", strings=F, header=T)