gpt4 book ai didi

r - 将代码块放在 if 语句中会更改分配行为 R

转载 作者:行者123 更新时间:2023-12-01 16:26:33 25 4
gpt4 key购买 nike

我遇到了一个非常好奇的 R 问题。我在 if 中有一大段代码分配列表元素的语句,但无论它是否在 if 中运行,它的 react 都不同语句(即使 if 语句是 if (1==1) {...} )或在它之外。

基本上,代码应该只是在做 if (true) {Raw[[1]]$params=params[[1]]; Raw[[2]]$params=params[[2]]; etc..} ,但最后,Raw[[1]]$params==Raw[[2]]$paramsRaw[[3]]$params==Raw[[4]]$params ,但前提是它在 if (true) {} 中陈述。如果它不在 if 内,它可以正常工作陈述。

让我举个例子(这是原始代码的一个大大简化的版本;rep 和列表分配的动机是出于与问题无关的变量管理原因):

#----- Create variables
# params is a 4-element list
params0 <- list(runif(2),runif(4),runif(6),runif(8))
# Raw is a 2-element list, of which every element is another (named) list
Raw0 <- list(list(data=runif(3),params=runif(2)),
list(data=runif(6),params=runif(6)))

dothing <- TRUE

#----- With if statement - does not correctly assign
Raw <- Raw0
params <- params0

if (dothing) {
Raw <- rep(Raw,each=2)
for (x in seq(1,length(params))) {
Raw[[x]]$params <- params[[x]]
}
}

# This should be false since params[[1]] ~= params[[2]], but returns true
identical(Raw[[1]],Raw[[2]])

#----- Without if statement - does correctly assign
Raw <- Raw0
params <- params0

Raw <- rep(Raw,each=2)
for (x in seq(1,length(params))) {
Raw[[x]]$params <- params[[x]]
}

# This returns false as expected
identical(Raw[[1]],Raw[[2]])

所有这一切中最后一个非常奇怪的皱纹 - 在原始代码中,如果代码逐 block 运行(没有丢失任何行),则分配工作正常,但如果整个代码一次运行,则分配不正确。

谁能告诉我我在这里缺少什么?预先感谢您的帮助!

最佳答案

观察到的行为与 if 无关环形。
如果您分配不同的结构,它将引发警告“要替换的项目数不是替换长度的倍数”。
我认为没有 - 在你的情况下 - Raw使用 $ 访问内容并替换为 params 的内容.

> str(Raw[[1]]$params)
num [1:2] 0.925 0.393
> str(params[[1]])
num [1:2] 0.177 0.986

#returns the content
> str(Raw[[1]]$params) #Used in your eg
num [1:2] 0.949 0.143
> str(Raw[[1]][[2]]) #Equivalent to the one used in your eg
num [1:2] 0.949 0.143

#returns the type of list
> str(Raw[[1]]["params"])
List of 1
$ params: num [1:2] 0.949 0.143

区别是 Raw[[1]]["params"]返回 listRaw[[1]]$paramsRaw[[1]][[2]]返回内容。

但实际上,当一个相同大小和类型的列表被另一个列表替换(这是替换长度的正确倍数)时,这会起作用。

更新代码:
#----- Create variables
# params is a 4-element list
params0 <- list(runif(2),runif(4),runif(6),runif(8))
# Raw is a 2-element list, of which every element is another (named) list
Raw0 <- list(list(data=runif(3),params=runif(2)),
list(data=runif(6),params=runif(6)))

dothing <- TRUE

#----- With if statement - does not correctly assign
Raw <- Raw0
params <- params0

if (dothing) {
Raw <- rep(Raw,each=2)
for (x in seq(1,length(params))) {
Raw[[x]]["params"] <- params[x] ##Note the way list is returned and list is replaced for another list.
}
}

#CORRECTED returns false: This should be false since params[[1]] ~= params[[2]], but returns true
identical(Raw[[1]],Raw[[2]])

关于r - 将代码块放在 if 语句中会更改分配行为 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54332442/

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