Home > Net >  convert string consisting of individual numbers and sequences to format which allows subsetting a ve
convert string consisting of individual numbers and sequences to format which allows subsetting a ve

Time:12-23

my problem refers to converting a string consisting of both individual numbers and sequences to a format, which allows me to subset a vector or dataframe. Background: The string originates from a cell in a .csv, which is read in as configuration-file and should be used for subsetting certain elements of a dataframe automatically/without typing it manually like my_vec[c(1,5,10:13,90)]. The sticking point is the sequence within the individual numbers. Otherwise a strsplit() by "," would deliver the desired result.

subsetting_string<-"1,5,10:13,90"

I want this string/character to be able to subset for example a vector from 1 to 100

my_vec<-seq(1,100,1)

to receive the result

[1] 1 5 10 11 12 13 90

Important: I´m not looking for the following procedure, I already know:

my_vec[c(1,5,10:20,90)]

But how can I convert/process the string (character) to be directly used as indexing element within the [] brackets? I had lots of tries with sub(), substr(), strsplit(), paste() and noquote(), but I always failed up to now.

Can anybody help me?

CodePudding user response:

We may split (strsplit) by comma (,) and loop over each of the elements with lapply/sapply, do an evaluation and unlist to create a vector

ind <- unlist(sapply(strsplit(subsetting_string, ",")[[1]], 
    function(x) eval(parse(text = x))), use.names = FALSE)

-output

> ind
[1]  1  5 10 11 12 13 90
  • Related