[英]Using data.table to calculate new columns
I have the following data 我有以下数据
set.seed(5)
dt <- data.table(ID=letters, x = rnorm(26), y = rnorm(26), z = c(rep(15, 13), rep(20,13)))
return, 返回,
ID x y z
1: a -0.84085548 1.41858907 15
2: b 1.38435934 1.49877383 15
3: c -1.25549186 -0.65708209 15
4: d 0.07014277 -0.85279544 15
5: e 1.71144087 0.31591504 15
6: f -0.60290798 1.10969417 15
7: g -0.47216639 2.21546057 15
8: h -0.63537131 1.21710364 15
9: i -0.28577363 1.47922179 15
10: j 0.13810822 0.95157383 15
11: k 1.22763034 -1.00953265 15
12: l -0.80177945 -2.00047274 15
13: m -1.08039260 -1.76218587 15
14: n -0.15753436 -0.14260813 20
15: o -1.07176004 1.55006037 20
16: p -0.13898614 -0.80242318 20
17: q -0.59731309 -0.07457892 20
18: r -2.18396676 1.89566795 20
19: s 0.24081726 -0.45656894 20
20: t -0.25935541 0.56222336 20
21: u 0.90051195 -0.88700851 20
22: v 0.94186939 -0.46024458 20
23: w 1.46796190 -0.72432849 20
24: x 0.70676109 -0.06921116 20
25: y 0.81900893 1.46324856 20
26: z -0.29348185 0.18772610 20
I am trying to update columns x
and y
by dividing both with z
, at the same time, keep the column ID
. 我试图通过用z
除以两者来更新列x
和y
,同时保留列ID
。 That is, the final output should contain columns ID
, x/z
, and y/z
也就是说,最终输出应包含列ID
, x/z
和y/z
I have try the following code, but it returns me the error 我尝试了以下代码,但它返回错误
dt[,c('x', 'y'):=lapply(.SD, function(x) x/z), .SDcols = names(dt)]
FYI, there are over 100 columns in the actual data that have to be divided by column z
. 仅供参考,实际数据中有超过100列必须按列z
划分。
Could you please give me suggestions? 你能给我一些建议吗?
Update: Issue #495 is solved now with this recent commit , we can now do this just fine: 更新:问题#495现在通过最近的提交解决了,我们现在可以做到这一点:
require(data.table) # v1.9.7+
nam <- setdiff(names(dt), c("ID", "z"))
dt[, (nam) := lapply(.SD, `/`, z), .SDcols = nam]
nam <- setdiff(names(dt), c("ID", "z"))
dt[, (nam) := lapply(.SD, `/`, dt[,z]), .SDcols = nam]
Note that i use dt[, z]
inside lapply
due this data.table
bug #495 . 请注意,由于这个data.table
错误#495 ,我在lapply
里面使用了dt[, z]
。
If you use .SDcols
you can not use other columns within your function calls. 如果使用.SDcols
,则不能在函数调用中使用其他列。
As a workaround, until #495 is done, you can use mget()
as follows: 作为一种解决方法,在#495完成之前,您可以使用mget()
,如下所示:
dt[, (nam) := lapply(mget(nam), `/`, z)]
How about 怎么样
dt[, `:=`(x=x/z, y=y/z, z=NULL)]
EDIT: After the addition to the original question that there are more than the two columns in the data table I'd go with Floo0's answer 编辑:在原始问题的补充之后,数据表中有两列以上我将使用Floo0的答案
Doesn't this work? 这不行吗?
dt$x <- dt$x / dt$z
dt$y <- dt$y / dt$z
dt <- dt[ , seq(1, 3)]
EDIT: If you have many columns you have to divide with z, you can try this instead: 编辑:如果你有很多列,你必须除以z,你可以尝试这样做:
dt[, seq(2, 101)] <- sapply(dt[, seq(2, 101)], '/', dt$z)
dt <- dt[, seq(1, 101)] #replace with boundaries of your choosing
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.