DavidF
DavidF

Reputation: 91

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

Upvotes: 4

Views: 1449

Answers (2)

Vincent
Vincent

Reputation: 17725

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

Upvotes: 2

akrun
akrun

Reputation: 886938

The CI is a list column. We can use transpose and assign (:=)

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

Upvotes: 3

Related Questions