gpt4 book ai didi

r - 为什么要赋值给引用(:=) give different results when running code say two or three times within data. 表格格式?

转载 作者:行者123 更新时间:2023-12-03 23:47:07 25 4
gpt4 key购买 nike

我感谢你们所有人的宝贵时间。我想要一张表格,第一列没有滞后,第二列有一个滞后,第三列有两个滞后,等等,如图所示。我有实际完成这项工作的代码,但前提是您运行该代码一次。如果您运行代码两三次,您会注意到发生了额外的转变(滞后)。无论代码运行多少次,如果你们中的任何人都可以帮助我获得相同的结果,我将不胜感激。

截屏:

library(dplyr)
library(data.table)
d <- structure(list(inv = c(20, 18, 46, 28, 10, 17, 96, 37), c = c(1, 0.999735, 0.912009, 0.596777,
0.293534, 0.122216, 0.046563, 0.016929)), row.names = c(NA, -8L), class = c("tbl_df", "tbl", "data.frame"))
G <- matrix(d$inv)
W <- matrix(d$c)
K <- cbind(W%x%t(G))
dtK <- data.table(K)
z <- dtK[, names(dtK) := Map(shift, .SD, seq_along(.SD)-1L, fill = 0), .SDcols = names(dtK)]
z

最佳答案

:= 运算符在 dtK 对象中通过引用进行赋值。

这意味着无论您是否将其分配给 dtK,原始 z 对象都会发生更改。

尝试运行以下命令,看看会发生什么:

dtK[, names(dtK) := Map(shift, .SD, seq_along(.SD)-1L, fill = 0), .SDcols = names(dtK)]
dtK
V1 V2 V3 V4 V5 V6 V7 V8
1: 20.00000 0.000000 0.000000 0.000000 0.00000 0.00000 0.00000 0
2: 19.99470 18.000000 0.000000 0.000000 0.00000 0.00000 0.00000 0
3: 18.24018 17.995230 46.000000 0.000000 0.00000 0.00000 0.00000 0
4: 11.93554 16.416162 45.987810 28.000000 0.00000 0.00000 0.00000 0
5: 5.87068 10.741986 41.952414 27.992580 10.00000 0.00000 0.00000 0
6: 2.44432 5.283612 27.451742 25.536252 9.99735 17.00000 0.00000 0
7: 0.93126 2.199888 13.502564 16.709756 9.12009 16.99550 96.00000 0
8: 0.33858 0.838134 5.621936 8.218952 5.96777 15.50415 95.97456 37

解决此问题的一种方法是使用 copy 制作副本:
dtK <- data.table(K)
z <- copy(dtK)[, names(dtK) := Map(shift, .SD, seq_along(.SD)-1L, fill = 0), .SDcols = names(dtK)]
dtK
V1 V2 V3 V4 V5 V6 V7 V8
1: 20.00000 18.000000 46.000000 28.000000 10.00000 17.000000 96.000000 37.000000
2: 19.99470 17.995230 45.987810 27.992580 9.99735 16.995495 95.974560 36.990195
3: 18.24018 16.416162 41.952414 25.536252 9.12009 15.504153 87.552864 33.744333
4: 11.93554 10.741986 27.451742 16.709756 5.96777 10.145209 57.290592 22.080749
5: 5.87068 5.283612 13.502564 8.218952 2.93534 4.990078 28.179264 10.860758
6: 2.44432 2.199888 5.621936 3.422048 1.22216 2.077672 11.732736 4.521992
7: 0.93126 0.838134 2.141898 1.303764 0.46563 0.791571 4.470048 1.722831
8: 0.33858 0.304722 0.778734 0.474012 0.16929 0.287793 1.625184 0.626373

查看 vignette("datatable-reference-semantics") 了解更多信息。

关于r - 为什么要赋值给引用(:=) give different results when running code say two or three times within data. 表格格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62027659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com