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?
Answer
You need to use $
operator to extract the values as vectors or use double brackets, i.e.
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 ...
No comments:
Post a Comment