将向量分配给R中数据表中特定的现有行 [英] Assign a vector to a specific existing row of data table in R

查看:53
本文介绍了将向量分配给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.

我从一个空的 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))

现在,我为 data.table 之外的一行计算一些值并将其放置在向量 vec 中,e。 g。:

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)

如何将vec的值分配给e。 G。 data.table 的第一行同时获得良好的性能(因为我也想一步一步地填充其他行)?

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

推荐答案

首先,您需要获取正确的列类型,因为您创建的 NA 矩阵是合乎逻辑的。通过为它们分配数字不会神奇地更改列类型。

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

然后您可以使用

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

这篇关于将向量分配给R中数据表中特定的现有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆