1

I have a data.table object with the following column. Doing an exp on one of the columns results in an error as shown below:

  data <-  data.table('Speed' = c(90, 95, 100, 30, 49, 45, 10, 82),
                      'Fuel' = c(0.5, 0.1, 0.3, 0.15, 5, 3, 4, 2))

speed_var='Speed'

exp(data[,c(speed_var)])

Error message is

non-numeric argument to mathematical function

Strangely doing exp(data[,'Speed']) is working but if I put the column name in a variable and access, I am getting this error. Thoughts? Thanks!

s_baldur
  • 29,441
  • 4
  • 36
  • 69
FlyingPickle
  • 1,047
  • 1
  • 9
  • 19
  • Not about the problem itself, but you're missing a closing `)`. I don't know data.table well, but it seems related to [this](https://stackoverflow.com/q/32184252/5325862) and the posts linking to it. Take a look at what you get with `data[,c(speed_var)]`: it's the name of the selected column, not the column itself – camille Dec 20 '19 at 01:29

1 Answers1

1

We can extract the column as a vector with [[

exp(data[[speed_var]])

Or another option if we need it as a data.table

exp(data[, ..speed_var])

Or specify the column in .SDcols and apply the exp on .SD`

data[, exp(.SD), .SDcols = speed_var]
akrun
  • 874,273
  • 37
  • 540
  • 662