-1

I want to do a for loop with lists.

I tried :

for(tri in tripletsFinaux){

   CoefsCrit = apprentissage(data,tri$concurrents,tri$client,tri$depot)

   /* I put actions here but you don't need to see it for my problem */

}

In my loop, I launch a function which need the different values of the list tri. Because tripletsFinaux is a dataframe. And I need the 3 values of each tri to perform my function apprentissage() in the for loop.

tripletsFinaux looks like :

head(tripletsFinaux,2)
    depot          client concurrents nbLignes
1 blablabla     blobloblo       tatata      131
2 bliblibli     blublbublu      tututu      231

My error is :

$ operator is invalid for atomic vectors

What can I do ? I don't know if the error is in the apprentissage() function or in the for loop

celianou
  • 207
  • 4
  • 25
  • Sounds like you don't have an object named `data`, so R assumes you are trying to use the built-in function `data()`. – Gregor Thomas Oct 24 '17 at 14:01
  • Yeah you are right ... my bad ! Now the problem is different `Error: $ operator is invalid for atomic vectors` and I don't know if it's in the function or the $ in tri$concurrents ... – celianou Oct 24 '17 at 14:02
  • 6
    Then it seems like `tri` isn't a list, it's an atomic vector. It's hard to keep guessing, maybe [you could make a reproducible example](https://stackoverflow.com/q/5963269/903061)? – Gregor Thomas Oct 24 '17 at 14:05
  • I edited my post – celianou Oct 24 '17 at 14:09
  • Are you trying to loop over rows or columns? I can't even tell. What is `apprentissage`? Based on your sample input, what values do you want `tri` to take? Maybe just run `for (tri in tripletsFinaux) {print(head(tri))}` and make sure your loop is doing what you want. – Gregor Thomas Oct 24 '17 at 14:15
  • For example, in the first iteration of the loop. I want `tri$concurrents = tatata`, `tri$client = blobloblo` and `tri$depot = blablabla`. Maybe I am not iterating on the good thing. apprentissage is a function I wrote and it works when I test it out of the loop. So I want tri like : `blablabla ; blobloblo ; tatata ; 131` – celianou Oct 24 '17 at 14:16
  • Eventually you can use `mapply()` or `Map()`. – jogo Oct 24 '17 at 14:33

1 Answers1

1

It seems like you want to loop over the rows, so:

for(i in 1:nrow(tripletsFinaux)){

   CoefsCrit = apprentissage(data, tripletsFinaux$concurrents[i], tripletsFinaux$client[i], triplentsFinaux$depot[i])

   # ...

}

The above is what you want. The way you have it, for (tri in tripletsFinaux) will loop over the columns, one column at a time. I was hoping that would be clear if you ran for (tri in tripletsFinaux) {print(head(tri))}.

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • That's it ! It works using `for(i in 1:nrow(tripletsFinaux))`, and calling `triplestFinaux[i,colName]` – celianou Oct 24 '17 at 14:36