1

I'm having a dataframe in which I'm reading from a test file as like below

    Country,count
    uk,34
    au,35
    us,53
    in,44

This is my R script. This is just an example. When I'm trying to access a dataframe variable outside the loop which get created inside the for loop , I'm getting object not found error. Even I tried using assign. Getting the same error. I'm using R version 2.15.1.

    args <- commandArgs()
    #Storing the filename in fn given next to "--args"
    fn <- args[which(args=="--args")+1]
    t<-read.table(fn,sep=",",header=TRUE,as.is=TRUE,quote="")
    t
    for (i in levels(t$Country)){
            if ( i == us ) {
            RES <<- t[t$Country == i,]
            }
    }
    RES

    > args <- commandArgs()
    > #Storing the filename in fn given next to "--args"
    > fn <- args[which(args=="--args")+1]
    > t<-read.table(fn,sep=",",header=TRUE,as.is=TRUE,quote="")
    > t
      Country count
    1      uk    34
    2      au    35
    3      us    53
    4      in    44
    > for (i in levels(t$Country)){
    +       if ( i == us ) {
    +       RES <<- t[t$Country == i,]
    +       }
    + }
    > RES
    Error: object 'RES' not found
    Execution halted

I belive, I'm doing something wrong. Please advise.

4
  • 1
    why do you assign locally <<- instead of <- ? Commented Sep 13, 2012 at 13:11
  • <<- is to declare/access a variable globally.. Also <- is not working. Commented Sep 13, 2012 at 13:14
  • Did you define the object us? Commented Sep 13, 2012 at 13:25
  • In my example I should have put as "us". replaced levels with unique works fine in my real scenario. Thank you.. Commented Sep 13, 2012 at 15:26

1 Answer 1

2

Most of the chances the if constraint is never met (i == us)

it will never be equal to us. try to remove the "levels"

 for (i in t$Country)
      if (i =="us")
Sign up to request clarification or add additional context in comments.

1 Comment

I replaced levels with unique(t$Country) it is working fine now.. Thank you very much for your great hint..

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.