Calculate mean of calculated values

I want to calculate the mean of the resulting values returned by abs(((column A - column B)/column A)*100)

So for example on mtcars data i try:

> mtcars
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
...

mean((abs(mtcars['cyl']-mtcars['mpg'])/mtcars['mpg'])*100)

Which gives me error:

Warning message: In mean.default((abs(mtcars["cyl"] - mtcars["mpg"])/mtcars["mpg"]) * : argument is not numeric or logical: returning NA

How can i fix this?


You need to use $ operator to extract the values as vectors or use double brackets, ie

mean((abs(mtcars[['cyl']]-mtcars[['mpg']])/mtcars[['mpg']])*100)
#[1] 64.13455

#or

 mean((abs(mtcars$cyl-mtcars$mpg)/mtcars$mpg)*100)
#[1] 64.13455

You can see the difference in structure,

str(mtcars['cyl'])
'data.frame':   32 obs. of  1 variable:
 $ cyl: num  6 6 4 6 8 6 8 4 4 6 ...

str(mtcars[['cyl']])
 num [1:32] 6 6 4 6 8 6 8 4 4 6 ...

str(mtcars$cyl)
 num [1:32] 6 6 4 6 8 6 8 4 4 6 ...

一个完美的选择:

library(dplyr)
mtcars %>% 
  summarise(Mean = mean(abs(cyl - mpg)/mpg) * 100)

      Mean
1 64.13455
链接地址: http://www.djcxy.com/p/24844.html

上一篇: Boxplot为两个因子列中的每个单独级别?

下一篇: 计算计算值的平均值