0

I am running a program that needs to do a task for iterations 1 to 100, then quit and start again and execute for iteration 101 to 200, etc. I thought I would accomplish this by sourcing the program and passing in the values. In my calling program I have

GlobVar1<-1:100
GlobVar2<-101:200
GlobVar3<-201:300

GlobVal<-2
source("C:/Users/JSparks/Documents/testreceiveargs.R")

and in the program C:/Users/JSparks/Documents/testreceiveargs.R

I have

for (i in (1:2))
{
  print(GlobVar3[i])
}

Which works fine (output is 201, 202). Or

for (i in (1:2))
{
  print(get(paste0("GlobVar",GlobVal)))
}

Which gives output [1] 101 102 103 etc.

But I need to be able to control the values of the looping variable in the new program, but when I try

for (i in (1:2))
{
  print(get(paste0("GlobVar",GlobVal,"[i]")))
}

It errors out with message Error in get(paste0("GlobVar", GlobVal, "[i]")) : object 'GlobVar2[i]' not found

How can I combine the paste and the get to get the values that I need, which in this case would be 101, 102. Help would be most appreciated.

1
  • I suspect this may be an XY problem. Commented Feb 5 at 14:09

3 Answers 3

3

Just switch to better practices.

GlobVar <- list(
  GlobVar1 = 1:100,
  GlobVar2 = 101:200,
  GlobVar3 = 201:300
)

GlobVal <- 2

for (i in (1:2)) {
  print(GlobVar[[GlobVal]][i])
}
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that you can paste a string together,

> paste0('GlobVar', GlobVal)
[1] "GlobVar2"

and get an object with that name,

> get(paste0('GlobVar', GlobVal))
  [1] 101 102 103 104 105 106 107 ...

but you need to subset after you've got it,

> get(paste0('GlobVar', GlobVal))[1:2] 
[1] 101 102

instead of including something in the name that doesn't exist.

> get(paste0('GlobVar', GlobVal, '[1:2]'))
Error in get(paste0("GlobVar", GlobVal, "[1:2]")) : 
  object 'GlobVar2[1:2]' not found

BTW, as you see, you probably don't need a loop at all, depends what you're doing with he result.

Comments

0

This should solve your current problem :

for (i in (1:2)) {
  print(get(paste0("GlobVar",GlobVal))[i])
}

2 Comments

Thanks. But I am not exactly sure what you mean by current problem. I am trying some new functionality in R and have asked 3 or 4 questions in the last few weeks. I thought that was what SO was for.
They mean that you're coding things in a way that is not R-like, and will likely lead to many problems. With the little context you've shared, we can solve the current problem easily, but we can't do much about the way you're doing things. Though I do think Roland's answer is a pretty good start - please pay attention to Roland's advice.

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.