R: How to remove quotation marks in a vector of strings, but maintain vector format as to call each individual value?

我怕爱的太早我们不能终老 提交于 2020-01-07 08:00:23

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/19750353/r-how-to-remove-quotation-marks-in-a-vector-of-strings-but-maintain-vector-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!