Reputation: 1399
How can I assign the same length n to multiple vectors, in one go?
At the moment I am stuck doing
length(vector_1) <- n
length(hello) <- n
....
....
length(cat) <- n
Many thanks
Upvotes: 2
Views: 773
Reputation: 49640
If your vectors need to be the same length then it is likely that they are all related somehow. If they are related then it is usually better to collect them all together into a single object rather than having them as individual vectors in the global workspace. One option would be to put them all in a list together. Once in the list you can loop through the list (for loop or `lapply' function) and assign the length to each element. A data frame (which is stored as a list, so the above would work the same) is another way to store vectors that requires them to be the same length.
Upvotes: 4
Reputation: 55350
I would do as @spdickson suggested.
If you have too many vectors, and want to iterate:
vars <- c("var1", "var2", ..., "varxyz")
for (v in vars)
assign(v, vector(mode="??", length=n))
## Put in whichever mode your vectors will be
Upvotes: 2