0

i have a data frame of one column with number in it (between 1 and 20), when i try to make a loop for i always get an error (condition have a length > 1) is there a way to fix it ? thanks in advance !

here is my code :

tab2 <- as.data.frame(tab1$nombre_total*tab1$nombre_total)
for (i in tab2) {
 print(i)
 if (i>10)
   print("ok")
}

Expecting "ok" to show at least one time, but get a message error

MrFlick
  • 195,160
  • 17
  • 277
  • 295
guillaume
  • 1
  • 1
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Why are you using `as.data.frame`? If you took that call out, it might do what you want. Or aat least make sure to iterate the values of the column with `for (i in tab2[[1]])` or `for (i in tab2[,1])` otherwise you will be iterating over the columns themselves. – MrFlick Aug 09 '23 at 14:16
  • A data.frame is a liist. What you are doing is tto loop trough the df's columns (or list members). So you have `i` equal to the first column and the condition is trying multiple comparisons, a total of `nrow(tab2)` comparisons. – Rui Barradas Aug 09 '23 at 14:16
  • This is a version of [Difference between `[` and `[[`](https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el) – Rui Barradas Aug 09 '23 at 14:18
  • after i retire as.data.frame it work thanks ! i understand the problem now. – guillaume Aug 09 '23 at 14:41

0 Answers0