-1

I need to create potentially a huge number of variables. I would like to name them

var.1, var.2, var.3 etc.

I am thinking about using a for loop. To experiment, I use only a single iteration, i.e. i=1. I've tried paste() and print(), but neither works.

paste("detect.","1", sep="") = 2
Error in paste("detect.", "1", sep = "") = 2 : 
target of assignment expands to non-language object

print("detect.","1", sep="") = 1
Error in print("detect.", "1", sep = "") = 1 : 
target of assignment expands to non-language object

I've also tried to add as.vector() and others, but none of them works.

If possible, can anyone provide a better solution without using for loops?

Thanks

wen
  • 1,875
  • 4
  • 26
  • 43
  • 3
    No, you don't need "to create potentially a huge number of variables". You need to learn how to work with lists and data.frames. – Roland Feb 07 '14 at 23:06
  • Could you elaborate a little? Thanks – wen Feb 07 '14 at 23:20
  • 1
    I don't know what is unclear about my advice. You shouldn't litter your global environment with many variables. You should put them in bigger data structures. R comes with functions that make it much easier to work with lists and data.frames than with many variables in your workspace. This is just generic advice and examples can be found all over the internet and on SO. If you need `assign` and `get` and aren't doing advanced stuff with environments, you are doing easy stuff in a complicated way. – Roland Feb 07 '14 at 23:26
  • You might find http://vita.had.co.nz/papers/tidy-data.html helpful as it lays out a way to organise your data in R in a way that makes it easy to use with existing tools. – hadley Feb 08 '14 at 15:07

1 Answers1

2

You want assign:

> assign(paste("detect.", "1", sep=""), 2)
> detect.1
[1] 2
Señor O
  • 17,049
  • 2
  • 45
  • 47
  • 1
    I'd still recommend @Roland 's advice. I don't know exactly what you're doing, but my guess is it's the kind of thing a list would be better for. It could be as simple as `detect = list(); for (i in 1:10) detect[i] = 2` – Señor O Feb 07 '14 at 23:34