Pascal
Pascal

Reputation: 1672

Assign a vector to a specific existing row of data table in R

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)?

Upvotes: 7

Views: 4218

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99391

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)]

Upvotes: 11

Related Questions