rvectorrangecatdput

Alternative to dput(), cat() to save vector to global env


I have several cases where I am trying to save a vector of elements to my global environment to be able to use for querying a database or other subsequent analyses.

As an example, I have a dataframe below, but in reality my data consists of thousands of values.

df:
example start   stop   range
set1    1       4180   1:4180
set2    460     499    460:499
set3    1       1127   1:1127
set4    1128    1622   1128:1622
set5    3741    3748   3741:3748

With this dataframe I want to capture every integer between start and stop, so I would like to use the range column to create a vector of every integer.

I have been using:

cat(paste0(df$range, collapse = ", "))

Which then prints to the console:

1:4180, 460:499, 1:1127, 1128:1622, 3741:3748

I have then been copy/pasting that output to save it as a vector in my global environment:

nums <- c(1:4180, 460:499, 1:1127, 1128:1622, 3741:3748)

Once I have this vector I can then do additional analyses such as:

> length(nums)
[1] 5850
> length(unique(nums))
[1] 4180
> summary(nums)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
      1     712    1443    1727    2726    4180

etc. etc.

Is there a simple way to skip the copy/paste step and save my desired formatting as a vector directly?


Solution

  • An option is Map to get the sequence (:) between the corresponding 'start', 'stop' values and unlist the list of vectors to a single vector.

    vec <- unlist(Map(`:`, df$start, df$stop))
    

    Or if we want to use the 'range' column, then evaluate it

    vec1 <- sapply(df$range, function(x) eval(parse(text = x)))