Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

data.table

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

like image 393
Pascal Avatar asked Jun 04 '16 17:06

Pascal


Video Answer


1 Answers

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)]
like image 117
Rich Scriven Avatar answered Sep 19 '22 03:09

Rich Scriven