0

I want to create a vector of names that act as variable names so I can then use themlater on in a loop.

years=1950:2012  
for(i in 1:length(years))  
{    
varname[i]=paste("mydata",years[i],sep="")   
}

this gives:

> [1] "mydata1950" "mydata1951" "mydata1952" "mydata1953" "mydata1954" "mydata1955" "mydata1956" "mydata1957" "mydata1958"
[10] "mydata1959" "mydata1960" "mydata1961" "mydata1962" "mydata1963" "mydata1964" "mydata1965" "mydata1966" "mydata1967"
[19] "mydata1968" "mydata1969" "mydata1970" "mydata1971" "mydata1972" "mydata1973" "mydata1974" "mydata1975" "mydata1976"
[28] "mydata1977" "mydata1978" "mydata1979" "mydata1980" "mydata1981" "mydata1982" "mydata1983" "mydata1984" "mydata1985"
[37] "mydata1986" "mydata1987" "mydata1988" "mydata1989" "mydata1990" "mydata1991" "mydata1992" "mydata1993" "mydata1994"
[46] "mydata1995" "mydata1996" "mydata1997" "mydata1998" "mydata1999" "mydata2000" "mydata2001" "mydata2002" "mydata2003"
[55] "mydata2004" "mydata2005" "mydata2006" "mydata2007" "mydata2008" "mydata2009" "mydata2010" "mydata2011" "mydata2012"

All I want to do is remove the quotes and be able to call each value individually.

I want:

>[1] mydata1950 mydata1951 mydata1952 mydata1953, #etc... 

stored as a variable such that

varname[1]        
> mydata1950    

varname[2] 
> mydata1951  

and so on.

I have played around with

cat(varname[i],"\n") 

but this just prints values as one line and I can't call each individual string. And

gsub("'",'',varname)

but this doesn't seem to do anything.

Suggestions? Is this possible in R? Thank you.

Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
user2905307
  • 77
  • 1
  • 1
  • 6

1 Answers1

3

There are no quotes in that character vector's values. Use:

 cat(varname)

.... if you want to see the unquoted values. The R print mechanism is set to use quotes as a signal to your brain that distinct values are present. You can also use:

print(varname, quote=FALSE)

If there are that many named objects in you workspace, then you need desperately to learn to use lists. There are mechanisms for "promoting" character values to names, but this would be seen as a failure on your part to learn to use the language effectively:

var <- 2

> eval(as.name('var'))
[1] 2
> eval(parse(text="var"))
[1] 2
> get('var')
[1] 2
IRTFM
  • 258,963
  • 21
  • 364
  • 487