SavedByJESUS
SavedByJESUS

Reputation: 3314

Can the paste() function produce numeric values?

I dynamically generate 5 variables each containing a random value:

> i = 1
> 
> while(i <= 5)
 {
   assign(paste("x", i, sep = ""), rnorm(1))
   i = i + 1       
 }
> x1
[1] 0.3853609
> x2
[1] 1.626055
> x3
[1] -1.043699
> x4
[1] 0.3449921
> x5
[1] -0.9768416

Is there any function in R that will allow me to dynamically display the value of each of the variables. What I mean is a function like:

> paste("x", 1, sep = "")
[1] "x1"

that would not produce a character string, but that would show the value of the variable x1. In this way, I could create a loop to display all the values.

Thanks for your help.

Upvotes: 1

Views: 1105

Answers (1)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

Why not make them in a single list object. Lists are great to work with because each element can hold objects of any type and can be of different sizes, so you don't need to guarantee the return value of your function produces an identically sized output. In this simple cases, I would use replicate to draw 5 independent random normal deviates:

 n <- 5
 x <- replicate( n , rnorm(1) , simplify = FALSE )
[[1]]
[1] 1.820713

[[2]]
[1] -0.2326797

[[3]]
[1] -0.7698173

[[4]]
[1] -0.3954702

[[5]]
[1] -0.5585051

You can access each element through subsetting with [[, e.g. to get the second result:

x[[2]]
[1] -0.2326797

Which I guarantee is much easier that working with 5 separate variables.

Upvotes: 2

Related Questions