gpt4 book ai didi

r - 在评估之前必须调用变量两次?

转载 作者:行者123 更新时间:2023-12-04 10:57:34 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





data.table objects assigned with := from within function not printed

(2 个回答)


5年前关闭。




这里正在发生一些非常奇怪的事情。在下面的代码中,我创建了一个名为 temp 的变量。 .我必须调用它两次才能看到它是什么。例如。我第一次调用它时,控制台什么也没显示。第二次显示 data.table/data.frame这是。谁能帮我理解这里发生了什么?

library(magrittr)
library(data.table)

myDT <- as.data.table(mtcars)


temp <-
myDT %>%
melt(id.vars = c('cyl', 'mpg', 'hp'),
measure.vars = c('vs','am','gear','carb'),
variable.name = 'Data') %>%
extract( value > 0) %>%
extract( , value := NULL)

我的控制台在做什么(第一次调用什么都不做):
> temp
> temp
cyl mpg hp Data
1: 4 22.8 93 vs
2: 6 21.4 110 vs
3: 6 18.1 105 vs
4: 4 24.4 62 vs
5: 4 22.8 95 vs
...
...

最佳答案

这是为了消除更大的错误而实现的修复程序的已知副作用。已记录在案 here ,作为 v1.9.6 版本“BUG FIXES”部分下的第一项。引用该链接:

if (TRUE) DT[,LHS:=RHS] no longer prints, #869 and #1122. Tests added. To get this to work we've had to live with one downside: if a := is used inside a function with no DT[] before the end of the function, then the next time DT or print(DT) is typed at the prompt, nothing will be printed. A repeated DT or print(DT) will print. To avoid this: include a DT[] after the last := in your function. If that is not possible (e.g., it's not a function you can change) then DT[] at the prompt is guaranteed to print. As before, adding an extra [] on the end of a := query is a recommended idiom to update and then print; e.g. > DT[,foo:=3L][]. Thanks to Jureiss and Jan Gorecki for reporting.



正如那里所解释的,解决方案是附加一个尾随 []到最后 := - 在您的函数中包含操作。在这里,这意味着执行以下操作:
library(magrittr)
library(data.table)
myDT <- as.data.table(mtcars)
temp <-
myDT %>%
melt(id.vars = c('cyl', 'mpg', 'hp'),
measure.vars = c('vs','am','gear','carb'),
variable.name = 'Data') %>%
extract( value > 0) %>%
extract( , value := NULL) %>% `[`

## Following which, this will print the first time
temp

关于r - 在评估之前必须调用变量两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34667536/

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