0

I have a character vector "x" that stores some values of the locations. When I run a while loop I get these locations

i <- 1
while (i < 5) {
    print(x[c(i)])
    i = i+1
}

Output is :

[1] "/SampleData/exp964/K8"
[1] "/SampleData/exp294/K9"
[1] "/SampleData/exp264/K3"
[1] "/SampleData/exp29/K1"

Now, what I want to do is to assign these outputs to an object something like this

s_1 = "/SampleData/exp964/K8"
s_2 = "/SampleData/exp294/K9"
s_3 = "/SampleData/exp264/K3"
s_4 = "/SampleData/exp29/K1"

so that I can point to any object or use it in my code just by using c(s(i)) or something like that.

Could someone please help me getting this wrkable.

Thank you

Angelo
  • 4,829
  • 7
  • 35
  • 56
  • 1
    You don't want to do that. You can always just do `x[1]`, or you can create names, like `names(x) <- paste0("s_",1:5)`, and then do `x["s_1"]`. – joran Nov 16 '18 at 23:55
  • @joran Thank you :) – Angelo Nov 16 '18 at 23:57
  • 1
    similar post - [One variable name combining a static name + a variable name](https://stackoverflow.com/questions/53250691/one-variable-name-combining-a-static-name-a-variable-name/53250742#comment93386535_53250742) – Shree Nov 17 '18 at 00:04

1 Answers1

2

Given

x <- c("/SampleData/exp964/K8", "/SampleData/exp294/K9", "/SampleData/exp264/K3", "/SampleData/exp29/K1")

you don't need to do any more assignments. Just as in your loop, you may use, e.g.,

x[2]
# "/SampleData/exp294/K9"

to get those values. Having a vector of values rather than several separate variables is much more convenient, flexible, and a better practice.

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
  • Thank you, sometimes a simple soluton is the need of the hour while we keep looking for the complicated ways – Angelo Nov 16 '18 at 23:58