Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been trying to get this R code to assign integers on the fly. It works when they are less than 99, but the else statement seems to not be working. I keep getting errors stating: object 'tmpvarname2' not found

R
parameters = c(6202, 5, 6401, 1)
listlength <- length(parameters)
sncount <- 1
tncount <-1
pcount <- 1

while(listlength>0) {
  
 if (parameters[pcount]>1000){
    tmpvarname1 <- assign(paste("sn", sncount, sep = ""),parameters[pcount])
   sncount <- sncount +1
  }
  
    if (parameters[pcount]<=99){
    tmpvarname2 <- assign(paste("tn", tncount, sep = ""),parameters[pcount])
    
   tncount <- tncount +1
   
    }
 listlength <- listlength-1
  pcount <- pcount +1
}
tmpvarname1
tmpvarname2


What I have tried:

I've tried using if - else with the second if statement as an else. Originally the full code read the parameters in as a text file, but even hard coding them did not fix that issue.
Posted
Updated 3-Aug-22 22:17pm
v3
Comments
Richard MacCutchan 3-Aug-22 3:56am    
Most likely because tmpvarname1 and tmpvarname2 only exist within the relevant if blocks. Try declaring the variables before the while statement so they are globally available.

1 solution

You need to declare tmpvarname1 and tmpvarname2 in the global space so they can be accessed inside and outside of the loop. You also need to use the global assignment operator (<<-) to update them inside the loop.
C
tmpvarname1 <- tmpvarname2 <- 0
while(listlength>0) {
  
 if (parameters[pcount]>1000){
    tmpvarname1 <<- assign(paste("sn", sncount, sep = ""),parameters[pcount])
   sncount <- sncount +1
  }
  
    if (parameters[pcount]<=99){
    tmpvarname2 <<- assign(paste("tn", tncount, sep = ""),parameters[pcount])
    
   tncount <- tncount +1
   
    }
 listlength <- listlength-1
  pcount <- pcount +1
}
tmpvarname1
tmpvarname2

You may want to do the same with sncount, tncount and pcount.

For further details see Scope of Variable in R - GeeksforGeeks[^].
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900