0

Today I have came across some strange problem. I have a data frame of 25 columns (let's say that this column is called Bitcoin). I have a loop and inside that loop I would like to read values from another columns:

for(i in 1:5)
{
  a <- a + (Bitcoin[1,5] - Bitcoin[1, 5 + i])
}

Assume that i=4. I should get the value of Bitcoin[1,9] which is 11400, but I always get the number of this column -> 9. When I write two formulas:

Bitcoin[1,9]
Bitcoin[1,5+i]

Values are different, the first is 11400 and the second is 9. Why this is happening?

ltrd
  • 326
  • 1
  • 8

1 Answers1

2

From ?data.table

. with=FALSE is often useful in data.table to select columns dynamically. Note that x[, cols, with=FALSE] is equivalent to x[, .SD, .SDcols=cols]

example:

aaa <- mtcars
setDT(aaa)
i=6
#eval step by step and see the outcome:
aaa[1,3+i]
aaa[1,3+i,with=FALSE]
aaa[, .SD, .SDcols=3+i]
aaa[1,9]
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69