[R] Converting a string to variable names

刘瑞阳 ruiyangliu94 at gmail.com
Wed Nov 15 23:22:14 CET 2017


Hi,

Thanks for your reply.

I just came up with another question about a similar but different thing:

Say I have a bunch of data.frame variables named P1,P2,P3… I want to assign them row names according to symbols in the first column, and I want to do this using a for loop. How could I accomplish this?


for (test_sample in c(1:10)){
+ x<-as.name(paste(“P",as.character(test_sampel),sep=""))
+ rownames(x)<-get((paste(“P”,as.character(test_sample),sep="")))[,1]
+ }

This would not work probably because x is simply a name instead of a data.frame variable(Error: "attempt to set 'rownames' on an object with no dimensions"). But I could not find the right way out… How should I solve it?

Thanks!

Ruiyang


> On Nov 14, 2017, at 4:39 PM, Jim Lemon <drjimlemon at gmail.com> wrote:
> 
> Hi Ruiyang,
> I think you want "get":
> 
> For (index in seq(1,16)){
> plot(x=(a given set of value),y=get(paste(“PC”,as.character(index),sep=“”)))
> }
> 
> On Wed, Nov 15, 2017 at 7:43 AM, 刘瑞阳 <ruiyangliu94 at gmail.com> wrote:
>> Hi,
>> Suppose that I want to do a series of plots with the y value for each plot as PC1, PC2, PC3… How could I accomplish this using a for loop?
>> Suppose the code like this:
>> 
>> For (index in seq(1,16)){
>> plot(x=(a given set of value),y=paste(“PC”,as.character(index),sep=“”)
>> }
>> 
>> But this would not work because y is assigned a string instead of the variable names. So how could I assign y with a variable name instead of a string? Your reply would be appreciated!
>> Ruiyang Liu
>> ______________________________________________
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list