0

I want to get values from an excel file, and assign certain values of them to arrays. At the beginning I tried the code below, and it worked. But after restarting r studio, and did everything again, it shows me this error

Error in USComp2005_2000_3000[m] = USComp2005$SIC[i] : object 'USComp2005_2000_3000' not found

I don't know how it worked in the beginning!

library(readxl)
USComp2005 <- read_excel("USCompanies2005.xlsx",sheet = "Data")
getValues <- function() 
{
 n=0
 m=0
 for (i in 1:6992) {
    if ((USComp2005$SIC[i] >= 6000) && (USComp2005$SIC[i] < 7000)) {
         n=n+1
         USComp2005_6000[n] = USComp2005$SIC[i]
     }
     else if ((USComp2005$SIC[i] >= 2000) && (USComp2005$SIC[i] < 4000)) {
         m=m+1
         USComp2005_2000_3000[m] = USComp2005$SIC[i]
     }
 }
}
Ali Zuhair
  • 303
  • 4
  • 17
  • hm `USComp2005_6000 <- USComp2005$SIC[(USComp2005$SIC >= 6000) & (USComp2005$SIC < 7000)]`? – jogo Apr 19 '17 at 09:31
  • Didn't work. When I run the function, the variable USComp2005_6000 isn't created. – Ali Zuhair Apr 19 '17 at 09:59
  • It works: `set.seed(42); d <- data.frame(a=rnorm(100), b=rnorm(100), c=sample(1100:2000, 100)); d[(d$a>0.7) & (d$b< -0.8),]; d$c[(d$a>0.7) & (d$b< -0.8)]` Please give a reproducable example! [mcve] and http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – jogo Apr 19 '17 at 11:44

1 Answers1

0

Variables created inside a for loop or a function in R have local scope (i.e. they are reachable only from within that loop). You should initialize the vectors before the loop, and then fill them. Something like:

USComp2005_6000 = USComp2005_2000_3000 = NULL
for (condition) {
  ...
  USComp2005_6000[n] = ...
  ...
}

One can also use global assignment:

function(){ USComp = ... } # USComp is local

USComp = NULL; function(){ USComp = ... } # global by initialization

function(){ USComp <<- ... } # global by assignment

But for your task, @jogo's vectorized solution in the comment is the best. Again, just make sure to initialize the vectors, or use global scope.

juod
  • 440
  • 3
  • 8