0

I would like to create a list of items and then move through the list one item at a time to replace one word in a section of my R script that will refer to various objects in order to simply.

For example, I start with this:

A <- mydata[1:48, "A"]
B <- mydata[1:48, "B"]
C <- mydata[1:48, "C"]

I want to simplify so it is one line of script but runs for values of x=A, x=B, and x=C where x is naming an object (no "") but also calling a column (inside "").

x <- mydata[1:48, "x"]
TJames
  • 35
  • 4
  • 1
    maybe you want to work with a list. see gregor's post on [this question](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) to learn more. – lmo Jan 05 '17 at 18:46

1 Answers1

0

You could solve the problem simply iterating a list of values and using the assign function (assign a value to a name in an environment).

Try this reproducible code:

> set.seed(123)
> my_data <- as.data.frame(matrix(rnorm(3*50), nrow=50, ncol=3))
> values_list <- c("A","B","C")
> colnames(my_data) <- values_list
> 
> for (v in values_list) {
+   assign(v,  my_data[1:48, v])
+ }
> A
 [1] -0.56047565 -0.23017749  1.55870831  0.07050839  0.12928774
 [6]  1.71506499  0.46091621 -1.26506123 -0.68685285 -0.44566197
[11]  1.22408180  0.35981383  0.40077145  0.11068272 -0.55584113
[16]  1.78691314  0.49785048 -1.96661716  0.70135590 -0.47279141
[21] -1.06782371 -0.21797491 -1.02600445 -0.72889123 -0.62503927
[26] -1.68669331  0.83778704  0.15337312 -1.13813694  1.25381492
[31]  0.42646422 -0.29507148  0.89512566  0.87813349  0.82158108
[36]  0.68864025  0.55391765 -0.06191171 -0.30596266 -0.38047100
[41] -0.69470698 -0.20791728 -1.26539635  2.16895597  1.20796200
[46] -1.12310858 -0.40288484 -0.46665535

As showed, you can use the variable A, B, C.

enneppi
  • 881
  • 12
  • 30
  • What added details would improve the quality? – TJames Jan 05 '17 at 18:52
  • for example what type of argument takes the nnetar function? – enneppi Jan 05 '17 at 18:54
  • In your answer, I want "result" to equal v without the quotation marks, such that A = mydata[1:48, "A"]. – TJames Jan 05 '17 at 19:15
  • For the simple example I provided, this answer works. I tried extending it to a more complex example that is truer to my end goal but did not have any luck. In the more complex example, I want to replace a portion of an object name (ex. x.df = A.df) but received an error. I plan to return to trying to get this to work once I've met my current project deadline. I'm new to R but have used SAS extensively and was hoping to find the R equivalent to the global macro variables. – TJames Jan 06 '17 at 19:41
  • accept the answer if solve the current question, then I suggest to make another question with all details to solve the new above mentioned error – enneppi Jan 06 '17 at 19:44