Home > Net >  Multiply list values by 100 using apply function
Multiply list values by 100 using apply function

Time:01-06

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!!

CodePudding user response:

Using example data of a list...

#Make list
n <- rnorm(12, mean = 0.00791, sd = 0.4)
n2 <- c(0.010, 0.0223, 0.0890, 0.034, 0.078, 0.0902, 0.034, 0.0211, 0.01007,0.0209, 0.0330, 0.0446)
data <- list(n, n2)

# apply x 100 to the data list
new_dataframe <- lapply(data,"*",100)

This will X100 to all components of the list. Without seeing your code, it is hard to give any more advice.

CodePudding user response:

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

CodePudding user response:

We can use double lapply, and somewhat keep the original data structure:

lapply(x, function(i) lapply(i, function(j) j  * 100))
# [[1]]
# [[1]]$conf.int
# [1]  5.4 57.0
# attr(,"conf.level")
# [1] 0.95
# 
# 
# [[2]]
# [[2]]$conf.int
# [1]  1.63800 40.03372
# attr(,"conf.level")
# [1] 0.95

Or we can avoid manipulating the output and fix the problem from the start, by multiplying data by 100 before computing the confidence intervals, for example:

t.test(mtcars$mpg, conf.level = 0.95)
#   One Sample t-test
# 
# data:  mtcars$mpg
# t = 18.857, df = 31, p-value < 2.2e-16
# alternative hypothesis: true mean is not equal to 0
# 95 percent confidence interval:
#  17.91768 22.26357
# sample estimates:
# mean of x 
#  20.09062 

t.test(mtcars$mpg * 100, conf.level = 0.95) 
#   One Sample t-test
# 
# data:  mtcars$mpg * 100
# t = 18.857, df = 31, p-value < 2.2e-16
# alternative hypothesis: true mean is not equal to 0
# 95 percent confidence interval:
#  1791.768 2226.357
# sample estimates:
# mean of x 
#  2009.062 
  • Related