[英]R, data.table: How to assign values of some columns based on the names of other columns, which are stored in a character vector?
I have the following data table: 我有以下数据表:
dt=data.table(a=seq(1,3),b=letters[seq(1,3)],
c=seq(4,6),d=letters[seq(4,6)])
dt
a b c d
1: 1 a 4 d
2: 2 b 5 e
3: 3 c 6 f
I store the names of some columns in one vector and the names of other columns in another vector: 我将一些列的名称存储在一个向量中,将其他列的名称存储在另一个向量中:
names1=names(dt)[1:2]
names2=names(dt)[3:4]
I need to assign the values of the columns stored in names2 to the columns of names1 when some conditions apply. 当某些条件适用时,我需要将names2中存储的列的值分配给names1的列。 Something like 就像是
dt[c(2,3),names1:=names2]
dt
a b c d
1: 1 a 4 d
2: 5 e 5 e
3: 6 f 6 f
I have tried the following syntax without success: 我尝试了以下语法但没有成功:
dt[c(2,3),names1:=dt[c(2,3),names2,with=F]]
But it still tries to assign the values of the string vectors contained in names2 但它仍然试图分配names2中包含的字符串向量的值
I would do 我会做
dt[2:3, (names1) := .SD, .SDcols = names2]
Or an alternative approach, thanks to @DavidArenburg: 或者另一种方法,感谢@DavidArenburg:
dt[c(2,3), (names1) := mget(names2)]
How it works 这个怎么运作
(names1) :=
ensure that we look at the content of the names1
vector instead of making a column named "names1"
. 正如@DavidArenburg解释的那样, (names1) :=
names1)中的括号(names1) :=
确保我们查看names1
向量的内容,而不是创建名为"names1"
的列。 .SDcols
. 我建议通过第一 .SDcols
插图获取有关.SDcols
详细信息。 mget
finds objects based on their names and puts them into a list. mget
根据名称查找对象并将其放入列表中。 I found that I can do this using with=F, is it inefficient in some way?. 我发现我可以用= F来做这个,它在某种程度上效率低吗?
The way I found it was like this: 我发现它的方式是这样的:
dt[c(2,3),names1:=dt[c(2,3),names2,with=F],with=F]
Any comments on the efficiency would be nicely received. 任何关于效率的评论都会很好地收到。
Thank you. 谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.