[R] How to use a text in an object of class character position to create a vector with the text as name

Sarah Goslee sarah.goslee at gmail.com
Tue Jul 17 20:39:30 CEST 2012


On Tue, Jul 17, 2012 at 2:23 PM, R. Michael Weylandt
<michael.weylandt at gmail.com> wrote:
> On Tue, Jul 17, 2012 at 10:55 AM, Sarah Goslee <sarah.goslee at gmail.com> wrote:
>> In general, you use assign() to do that, but having object names
>> containing spaces should be avoided.
>>
>>> mytext <- "Experiment name : CONTROL DB AD_1"
>>> mytext
>> [1] "Experiment name : CONTROL DB AD_1"
>>> mytext <- sub("Experiment name : ", "", mytext)
>>> mytext
>> [1] "CONTROL DB AD_1"
>>>
>>> assign(mytext, 1:10)
>>> ls()
>> [1] "CONTROL DB AD_1" "mytext"
>>> "CONTROL DB AD_1"
>> [1] "CONTROL DB AD_1"
>>>
>>>
>>> CONTROL DB AD_1
>> Error: unexpected symbol in "CONTROL DB"
>>
>> Since you can't access your object by typing its name at the R prompt,
>> either with or without quotes, you've kind of got a problem. You could
>> use get(), but at that point why not just name your object something
>> that follows the R naming conventions?
>
> I know Sarah knows this, but just for archive completeness: backticks.

I knew I was missing something.

> `cat or dog` <- 3
>
> cat or dog # Error
>
> `cat or dog` # 3
>
> Of course, this allows such insanity as
>
> `4` <- 15
>
> which is somewhat peculiar.
>
> I still second the advice to use legal R names and uses underscores
> where spaces might be desired.

So true.

And for convenience:
> mytext <- gsub(" ", "_", mytext)
> mytext
[1] "CONTROL_DB_AD_1"


> raw_data <- 3
>
> etc.
>
> Best,
> Michael
>
>>
>> Sarah
>>
>> On Tue, Jul 17, 2012 at 11:08 AM, benji <benlucas at illinois.edu> wrote:
>>> Hello,
>>>>titletool<-read.csv("TotalCSVData.csv",header=FALSE,sep=",")
>>>
>>>> class(titletool)
>>> [1] "data.frame"
>>>
>>>>titletool[1,1]
>>> [1] Experiment name : CONTROL DB AD_1
>>>
>>>>t<-titletootl[1,1]
>>>
>>>>t
>>> [1] Experiment name : CONTROL DB AD_1
>>>
>>>>class(t)
>>> [1] "character"
>>>
>>> now i want to create an object (vector) with the name "Experiment name :
>>> CONTROL DB AD_1" , or even better if possible CONTROL DB AD_1
>>>
>>> Thank you
>>>
>>

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list