简体   繁体   English

提取置信区间 data.table

[英]Extracting Confidence Intervals data.table

What I want to do is to have columns for the upper and lower confidence interval for a proportion.我想要做的是为比例的上下置信区间设置列。

Here is what I have done:这是我所做的:

> #Create some sample data
> Frustration <- data.table(group = c('A','B','C'), trials = c(363,1398,139), surg = c(57,276,18))
> Frustration
   group trials surg
1:     A    363   57
2:     B   1398  276
3:     C    139   18
> 
> #try to get confidence levels. what I am expecting is CI to be a list of 2 elements, for each value of group, but I don't think that is working
> F2 <- Frustration[, .(CI = prop.test(surg, trials, conf.level = .75)['conf.int']), by = .(group)]
> F2
   group                    CI
1:     A   0.1350140,0.1816828
2:     B   0.1851178,0.2103210
3:     C 0.09701967,0.16972056
> 
> #lower is still a list here - I am stumped
> F3 <- F2[, .(lower = CI[[1]]), by = .(group)]
> F3
   group                 lower
1:     A   0.1350140,0.1816828
2:     B   0.1851178,0.2103210
3:     C 0.09701967,0.16972056

I think by confusion has to do with lists, and how data table handles the return.我认为混淆与列表有关,以及数据表如何处理返回。

Thanks for your help,谢谢你的帮助,

David大卫

The CI is a list column. CI是一个list列。 We can use transpose and assign ( := )我们可以使用transpose和赋值( :=

library(data.table)
F2[, c('lower', 'upper') := data.table::transpose(CI)][, CI := NULL][]
#Key: <group>
#    group      lower     upper
#   <char>      <num>     <num>
#1:      A 0.13501400 0.1816828
#2:      B 0.18511780 0.2103210
#3:      C 0.09701967 0.1697206

The other solution works, but here's a simple one-liner:另一个解决方案有效,但这里有一个简单的单行:

library(data.table)

Frustration <- data.table(group = c('A','B','C'), trials = c(363,1398,139),
                          surg = c(57,276,18))

Frustration[, c("lower", "upper") := 
              as.list(prop.test(surg, trials, conf.level = .75)$conf.int), 
            by=group][]
#>    group trials surg      lower     upper
#> 1:     A    363   57 0.13501400 0.1816828
#> 2:     B   1398  276 0.18511780 0.2103210
#> 3:     C    139   18 0.09701967 0.1697206

And even simpler, but you'll have to do some renaming:甚至更简单,但您必须进行一些重命名:

Frustration[, as.list(prop.test(surg, trials, conf.level = .75)$conf.int), by=group]
#>    group         V1        V2
#> 1:     A 0.13501400 0.1816828
#> 2:     B 0.18511780 0.2103210
#> 3:     C 0.09701967 0.1697206

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM