Search code examples
rapply

Multiply list values by 100 using apply function


I would like to multiply list values by 100. That is, 0.0549 would be 5.49, 0.5719 would be 57.19, 0.0166 would be 1.66, etc.

#example data
x <- list(structure(list(conf.int = structure(c(0.054, 0.57), conf.level = 0.95)), 
                    class = "htest"),
          structure(list( conf.int = structure(c(0.01638, 0.4003372 ), conf.level = 0.95)), 
                    class = "htest"))

x
# [[1]]
# data:  
# 
# 95 percent confidence interval:
#  0.054 0.570
# 
# [[2]]
# data:  
# 
# 95 percent confidence interval:
#  0.0163800 0.4003372

How would I get this? thanks in advance!!


Solution

  • The apply family is not needed in this instance I think. You seem to have a list of lists, and each sub-list contains a single named value. EDIT: This assumption is wrong, I misread the screenshot, leaving the error here for posterity) :EDIT

    mocking up data:

    a <- list(list(conf.int = 1.2), list(conf.int = 0.0166), list( conf.int = 0.95))
    

    if we try a * 100 we get an error:

    > a*100
    Error in a * 100 : non-numeric argument to binary operator
    

    So we need to simplify the list into a numeric vector using unlist():

    > unlist(a)*100
    conf.int conf.int conf.int 
      120.00     1.66    95.00 
    

    If you really want an apply() variant, perhaps:

    > sapply(a, FUN = \(x) {x$conf.int * 100})
    [1] 120.00   1.66  95.00