Monday 19 March 2018

Working with R Objects


When you create R objects and wants to retrieve the contents of the R object by iterating through the names recorded in the environment, get() is a useful function to use which avoids having to type out each of the object individually.

Example:

VECTOR1 <- sample(LETTERS, 10)
VECTOR1  

[1] "Y" "V" "T" "D" "K" "R" "W" "L" "Q" "J"  
 
VECTOR2 <- sample(letters, 30, replace = T)
VECTOR2  

 [1] "q" "i" "m" "u" "p" "e" "u" "t" "l" "t" "z" "k" "h" "u" "h" "o" "d" "t" "z" "n" "q" "a" "k" "b" "s" "e" "j"   
[28] "l" "k" "i"  
 
VECTOR3 <- runif(13)
VECTOR3  

[1] 0.73954457 0.19358300 0.04297713 0.99239641 0.28687096 0.47457809 0.10748857 0.83374202 0.66029667 0.74115429  
[11] 0.23601701 0.11957657 0.81442439  
   
LS <- ls(pattern = "^VECTOR")
LS  

[1] "VECTOR1" "VECTOR2" "VECTOR3"  
 
get(LS[1])  
 [1] "Y" "V" "T" "D" "K" "R" "W" "L" "Q" "J"  
 
get(LS[2])  
 [1] "q" "i" "m" "u" "p" "e" "u" "t" "l" "t" "z" "k" "h" "u" "h" "o" "d" "t" "z" "n" "q" "a" "k" "b" "s" "e" "j"  
[28] "l" "k" "i"  
 

No comments:

Post a Comment