【问题标题】:How to get values from an r vector of objects out into a vector?如何从对象的 r 向量中获取值到向量中?
【发布时间】:2012-07-04 19:31:23
【问题描述】:

我想不出如何给这个命名,我所拥有的是一个由这种形式的函数(特别是 midPci)生成的对象向量:

$conf.int
[1] 0.4726 0.6466
attr(,"conf.level")
[1] 0.95

$conf.int
[1] 0.1181 0.2566
attr(,"conf.level")
[1] 0.95

我想要做的是将$conf.int 的两个值剥离成向量,给出置信区间的上限和下限。显然我可以通过循环来做到这一点,但我认为可能有更好的方法来做到这一点?

CIs <- structure(list(conf.int = structure(c(0.4696, 0.6501), conf.level = 0.95), 
 conf.int = structure(c(0.5266, 0.7081), conf.level = 0.95), conf.int = structure(c(0.4441, 
 0.6196), conf.level = 0.95), conf.int = structure(c(0.4181, 0.5891), conf.level = 0.95), 
 conf.int = structure(c(0.4726, 0.6466), conf.level = 0.95), conf.int = structure(c(0.1181, 
 0.2566), conf.level = 0.95), conf.int = structure(c(0, 0.000748652688017826), conf.level = 
 0.95)), .Names = c("conf.int", "conf.int", "conf.int", "conf.int", "conf.int", "conf.int", 
 "conf.int" ))

如果我的意思不清楚,我已经这样做了:

# Calculate CIs
CIs <- mapply(midPci, k, n, conf.level=0.95)

我可以通过CIs[1]$conf.int[1] 等获得我所追求的个人价值观,但我想一口气搞定全部。我可以这样做吗?

【问题讨论】:

    标签: r vector


    【解决方案1】:

    这会产生一个矩阵:

    do.call(rbind, CIs)
    
               [,1]         [,2]
    conf.int 0.4696 0.6501000000
    conf.int 0.5266 0.7081000000
    conf.int 0.4441 0.6196000000
    conf.int 0.4181 0.5891000000
    conf.int 0.4726 0.6466000000
    conf.int 0.1181 0.2566000000
    conf.int 0.0000 0.0007486527
    

    这也会产生一个矩阵,尽管它是“宽版本”。应用于向量的 c 函数只返回自身,您可以使用 as.vectorI 并获得相同的结果。真正起作用的是 sapply 调用的函数 simplify2array(CIs)

     sapply(CIs, "c")
         conf.int conf.int conf.int conf.int conf.int conf.int     conf.int
    [1,]   0.4696   0.5266   0.4441   0.4181   0.4726   0.1181 0.0000000000
    [2,]   0.6501   0.7081   0.6196   0.5891   0.6466   0.2566 0.0007486527
    

    如果我们使用do.call(cbind, CIs),我们也会得到“宽版本”。

    【讨论】:

    • 结构(列表(conf.int =结构(c(0.4696,0.6501),conf.level = 0.95),conf.int =结构(c(0.5266,0.7081),conf.level = 0.95) ),conf.int =结构(c(0.4441,0.6196),conf.level = 0.95),conf.int =结构(c(0.4181,0.5891),conf.level = 0.95),conf.int =结构(c( 0.4726, 0.6466), conf.level = 0.95), conf.int = structure(c(0.1181, 0.2566), conf.level = 0.95), conf.int = structure(c(0, 0.000748652688017826), conf.level = 0.95 )), .Names = c("conf.int", "conf.int", "conf.int", "conf.int", "conf.int", "conf.int", "conf.int") )
    • 这是 dput(CI)。在提出 R 问题时发布 dput 输出通常有用吗?我对它很陌生。
    • 是的,它通常很有用,并且受到高度赞赏,但前提是您将生成的输出粘贴到原始问题的编辑中。 (就像我刚刚做的那样,有一些换行符使它不会消失在右边。)
    猜你喜欢
    • 2021-09-02
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2012-08-31
    • 2019-05-13
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多