将范围内的输出列值替换为“True”

时间:2018-04-27 02:12:37

标签: r mcmc r-mice

我正在尝试编写一个涉及MICE包的函数,并且想要指定插补数据集中的马尔可夫链是否已经按照Rhat.mice中使用的Gelman和Rubin统计量的标准收敛(来自包“miceadds”)通过将Rhat.M.imp和Rhat.Var.imp中的.999和1.001之间的所有值替换为“TRUE”。作为参考,这是Rhat.mice的示例输出:

> testagain<- Rhat.mice(ini)
>     variable  MissProp Rhat.M.imp Rhat.Var.imp
>1        agep  5.681818   1.015537     1.021311
>2       alcgp 18.181818   1.002916     1.007297
>3       tobgp 17.045455   1.026634     1.042405
>4     disease  1.136364   1.014819           NA

这是我试图使用的代码(我得到错误错误:意外'&lt;'in“testagain $ Rhat.M.imp [(0.999)

 testagain$Rhat.M.imp[(0.999<testagain$Rhat.M.imp<1.001]<- TRUE

我想要输出如下

1.015537 
1.002916
1.026634
1.014819

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我建议改为创建一个新变量,但是如果你想这样做,你可以将Rhat.M.imp强制转换为字符变量。

df <- read.table(text = t, header = T, strip.white = TRUE)

library(dplyr)
df %>% mutate(
  Rhat.M.imp = case_when(1 < Rhat.M.imp & Rhat.M.imp < 1.01~as.character(TRUE), TRUE~as.character(Rhat.M.imp))
)

#   variable MissProp Rhat.M.imp Rhat.Var.imp
# 1     agep    5.682   1.015537        1.021
# 2    alcgp   18.182       TRUE        1.007
# 3    tobgp   17.045   1.026634        1.042
# 4  disease    1.136   1.014819           NA

这是数据集。

t <- "variable  MissProp Rhat.M.imp Rhat.Var.imp
        agep  5.681818   1.015537     1.021311
       alcgp 18.181818   1.002916     1.007297
       tobgp 17.045455   1.026634     1.042405
     disease  1.136364   1.014819           NA"

df <- read.table(text = t, header = T, strip.white = TRUE)
相关问题