I've been looking through tutorials and documentation, but have not figured out how to assign a vector of values for all columns to one existing row in a data.table
.
I start with an empty data.table
that has already the correct number of columns and rows:
dt <- data.table(matrix(nrow=10, ncol=5))
Now I calculate some values for one row outside of the data.table
and place them in a vector vec
, e. g.:
vec <- rnorm(5)
How could I assign the values of vec to e. g. the first row of the data.table
while achieving a good performance (since I also want to fill the other rows step by step)?
First you need to get the correct column types, as the NA
matrix you've created is logical. The column types won't be magically changed by assigning numerics to them.
dt[, names(dt) := lapply(.SD, as.numeric)]
Then you can change the first row's values with
dt[1, names(dt) := as.list(vec)]
That said, if you begin with a numeric matrix you wouldn't have to change the column types.
dt <- data.table(matrix(numeric(), 10, 5))
dt[1, names(dt) := as.list(vec)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With