0

I am trying to create a loop that generates variables. But I need a way to name the variables using an input method. What is the convention for inputting string names in variable generating

x="Variable" y="weight" z="height"

xy=paste(x,y,sep="") xz=paste(x,y,sep="")

xy_one=1:10 xy_two=11:20

So xy_one should be named VariableWeight_one and xz_two should be names Variableheight_two

2 Answers 2

1

Agree with Carl not to do it that way but I think his approach could be improved by using "[[" rather than "$". Try:

myVars<-list()
x="Variable"; y="Weight"; z="Height"
myVars[[ paste(x,y,"_one", sep="")]] <- 1:10
myVars[[ paste(x,z,"_one", sep="")]] <- 11:20

If you really still want to construct names I'll compose a suitable addition:

 x="Variable"; y="Weight"; z="Height"
 assign( paste(x,y,"_one", sep=""),  1:10)
 assign( paste(x,z,"_one", sep=""), 11:20)
 ls(patt="Variable")
[1] "VariableHeight_one" "VariableWeight_one"

Compare the effort (and language circumlocutions) it might take to find the first variable you created using your approach with with how simple it would be to extract the first element from myVars:

 eval(parse( text=ls(patt="Variable")[1] ))
# [1] 11 12 13 14 15 16 17 18 19 20

  myVars[[1]]
# [1]  1  2  3  4  5  6  7  8  9 10

(Furthermore, it wasn't even the right one.)

Sign up to request clarification or add additional context in comments.

Comments

1

The real answer is: don't do it that way. It's much easier, and more productive, to create a list or dataframe variable, dump your data into elements of same, and then assign names to these elements. In your case,

mydata<- list()
mydata$VariableWeight_one <- xy_one
mydata$Variableheight_two <- xy_two

3 Comments

Thank you for the repsonse Carl. But at the end of the day, I am trying to create a way to generate variables throughout a loop. I need the convention used in R to input strings into variables names.
for (i in c("abe","john","ryan","carl") {i_score=i}
@jessica then you'll have to look into the infamous eval(parse(foo)) construct -- or DWin's assign() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.