How do I get the output columns of ns/bs into a data.table in R?

185 views Asked by At

I have a data.table of features for example:

library(data.table)
m = data.table(x1=rnorm(10),x2=rnorm(10))

Normally if I wanted a natural spline basis expansion for one of the features in lm I could do something like:

library(splines)
m[,lm(x2 ~ ns(x1,df=4))]

But if all I want is to add the spline basis columns to my data.frame for later the following does not work:

m[,c('a','b','c','d') := ns(x1,df=4)]

Is there an elegant way to assign them? Without manually extracting columns like this:

foo = ns(m$x1,df=4)
m[,a:=foo[1,]] #etc
0

There are 0 answers