2

I'm running nested loops in R and keep getting an error. I keep getting an unexpected 'in' error.

rowcounter=0
for (item in nrs$hesid){
    rowcounter<-rowcounter+1
    for (name in colnames(all)){
        if (item in name){
            all['all','name']<-nrs[rowcounter,'TPM']
        }
    }
}

when I run it

rowcounter=0
>for (item in nrs$hesid){
+ rowcounter<-rowcounter+1
+ for (name in colnames(all)){
+ if (item in name){
Error: unexpected 'in' in:
"for (name in colnames(all)){
if (item in"
> all['all','name']<-nrs[rowcounter,'TPM']
Error in x[...] <- m : replacement has length zero
> }
Error: unexpected '}' in "}"
> }
Error: unexpected '}' in "}"
> }
Error: unexpected '}' in "}"
camille
  • 16,432
  • 18
  • 38
  • 60
econ
  • 19
  • 2

1 Answers1

0

%in% vs in

%in% is a vastly underused operator in R that checks for the element x in the set (vector) X, and outputs a logical result T or F. By contrast, for loops require the in keyword to iterate through members of a set, typically expressed as integers in the form start:finish although what you have here in names in colnames(all)will work.

"Hello" %in% c("Hello", "Hi", "Salutations") # TRUE
"Goodbye" %in% c("Hello", "Hi", "Salutations") # FALSE

So if all else in your code is correct (no way to know without a reproducible example), then this should work:

rowcounter=0
for (item in nrs$hesid){
    rowcounter<-rowcounter+1
    for (name in colnames(all)){
        if (item %in% name){
            all['all','name']<-nrs[rowcounter,'TPM']
        }
    }
}
Felix T.
  • 520
  • 3
  • 11