0

我想创建一个名称向量作为变量名称,以便稍后在循环中使用它们。

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

这给出了:

> [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"

我要做的就是删除引号并能够单独调用每个值。

我想:

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

存储为变量,使得

varname[1]        
> mydata1950    

varname[2] 
> mydata1951  

等等。

我玩过

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

但这只是将值打印为一行,我不能调用每个单独的字符串。和

gsub("'",'',varname)

但这似乎无济于事。

建议?这在R中可能吗?谢谢你。

4

1 回答 1

3

该字符向量的值中没有引号。利用:

 cat(varname)

....如果您想查看未引用的值。R 打印机制设置为使用引号向您的大脑发出信号,表明存在不同的值。您还可以使用:

print(varname, quote=FALSE)

如果您的工作区中有这么多命名对象,那么您需要拼命学习使用列表。有一些机制可以将字符值“提升”为名称,但这将被视为您学习有效使用该语言的失败:

var <- 2

> eval(as.name('var'))
[1] 2
> eval(parse(text="var"))
[1] 2
> get('var')
[1] 2
于 2013-11-03T06:50:10.257 回答