FlyingPickle
FlyingPickle

Reputation: 1133

non-numeric argument to mathematical function error in R

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!

Upvotes: 1

Views: 1082

Answers (1)

akrun
akrun

Reputation: 887891

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]

Upvotes: 1

Related Questions