[R-sig-Epi] converting string to a object name of a dataset

David Winsemius dwinsemius at comcast.net
Fri Mar 18 18:19:22 CET 2011


On Mar 18, 2011, at 11:18 AM, Madan Gopal Kundu wrote:

> Hi,
>
> Thanks to David and Bendix for giving me the solution. I would like to
> extend my question little bit further. I am trying to execute
> following code:
>
> data1<- data.frame(x=c(1:4), y=rep(1:4))

Did you mean to type:

  data1<- data.frame(x=c(1:4), y=rep(1, 4))  # ?

 > data1
   x y
1 1 1
2 2 1
3 3 1
4 4 1

> gvars<- c("x", "y")
> for (i in 1:2)
> {
> print(data1[[gvars[i]]])
> }
>
> and it returns the following output:
> [1] 1 2 3 4
> [1] 1 2 3 4
>
> However, my desired output is
> [1] 1 2 3 4
> [1] 1 1 1 1
>
> I tried the following code as well, but the problem remains same:
> attach(data1)
> for (i in 1:2)
> {
> print(get(gvars[i]))
> }
>
> Thanks in advance!!
>
> Regards
> Madan
>
> On Fri, Mar 18, 2011 at 3:19 AM, BXC (Bendix Carstensen)  
> <bxc at steno.dk> wrote:
>> get() looks in the search path, so you can put data 1 there using  
>> attach():
>>
>>> data1<- data.frame(x=c(1:4), y=rep(1,4))
>>> attach(data1)
>>> gvars<- c("x", "y")
>>> get( gvars[1] )
>> [1] 1 2 3 4
>>> get( gvars[2] )
>> [1] 1 1 1 1
>>
>> Best regards,
>> Bendix Carstensen
>> _________________________________________
>>
>> Bendix Carstensen
>> Senior Statistician
>> Steno Diabetes Center A/S
>> Niels Steensens Vej 2-4
>> DK-2820 Gentofte
>> Denmark
>> +45 44 43 87 38 (direct)
>> +45 30 75 87 38 (mobile)
>> bxc at steno.dk    www.biostat.ku.dk/~bxc
>> www.steno.dk
>>
>>> -----Original Message-----
>>> From: r-sig-epi-bounces at r-project.org
>>> [mailto:r-sig-epi-bounces at r-project.org] On Behalf Of Madan
>>> Gopal Kundu
>>> Sent: 18. marts 2011 06:19
>>> To: r-sig-epi at r-project.org
>>> Subject: [R-sig-Epi] converting string to a object name of a dataset
>>>
>>> Hi,
>>>
>>> I am trying to access object which is variable of a dataset
>>> using string.  For that I am trying to convert a string to
>>> the object name in the following code. But unfortunately it
>>> looks something is going wrong in the following code.
>>>
>>> data1<- data.frame(x=c(1:4), y=rep(1:4))
>>> gvars<- c("x", "y")
>>> z<- paste("data1", gvars[1], sep="$")
>>> get(z)
>>>
>>> The above code should return following output:
>>> [1] 1 2 3 4
>>>
>>> but instead it is printing following error "Error in get(z) :
>>> object 'data1$x' not found"
>>>
>>> Please help me to fix the problem.
>>>
>>> Regards
>>> Madan
>>>
>>> _______________________________________________
>>> R-sig-Epi at r-project.org mailing list
>>> https://stat.ethz.ch/mailman/listinfo/r-sig-epi
>>>

David Winsemius, MD
West Hartford, CT



More information about the R-sig-Epi mailing list