JohnS
JohnS

Reputation: 21

R Loops With Global Variables

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.

Upvotes: 0

Views: 71

Answers (3)

jay.sf
jay.sf

Reputation: 73272

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.

Upvotes: 1

Roland
Roland

Reputation: 132864

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])
}

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 389135

This should solve your current problem :

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

Upvotes: 0

Related Questions