[R-sig-Epi] converting string to a object name of a dataset
David Winsemius
dwinsemius at comcast.net
Fri Mar 18 14:35:43 CET 2011
On Mar 18, 2011, at 3:19 AM, BXC (Bendix Carstensen) 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
Many R users make an effort to avoid using `attach` in any setting
other than the very earliest efforts at learning R. As a result they
also avoid the use of "$" in coding, since it is much less flexible
than the function on which it depends, namely "[[". If you want the
string "x" to beinterpreted as a columnname then "[[" is the way to go:
> data1<- data.frame(x=c(1:4), y=rep(1,4))
> gvars<- c("x", "y")
#Two methods get you the results you want:
> data1[[gvars[1] ]]
[1] 1 2 3 4
> get("data1")[[ gvars[1] ]]
[1] 1 2 3 4
--
David.
>
> 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
>>
> _______________________________________________
> 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