Víctor
Víctor

Reputation: 23

How to read a vector as input user in R

I'm new using R and while I was working I had a question that I haven't been able to solve for myself. I would like to create a script or sequence in the console which let user introduce a vector as input, but not any vector, in particular, I need to introduce the vector: j<-c(1:20,4,30:35).

However, if I've tried to use:

limStr <- readline("Enter the vector you want:");
Enter the vector you want: j<-c(1:20,4,30:35)
lim <- as.numeric(unlist(strsplit(limStr, ","))); 

And I have got lim= NA 4 NA

Could someone help me with this problem? How should I write the sequences? Thanks.

Upvotes: 2

Views: 2459

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50668

You can use the (in)famous eval(parse(text = ...) construct:

limStr <- readline("Enter the vector you want:");
Enter the vector you want: c(1:20, 4, 30:35);    
lim <- eval(parse(text = limStr));
lim;
# [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20  4 30 31 32 33
#[26] 34 35 

On second thought, I'm not entirely sure what you want. If this is about extracting the comma separated terms, you can do

unlist(strsplit(gsub("(c\\(|\\))", "", limStr), ", "));
#[1] "1:20"  "4"     "30:35"

Upvotes: 1

Related Questions