salisbury_sainsburys
salisbury_sainsburys

Reputation: 21

mean() function returns NAs inexplicably

I'm trying to generate a mean of rows of numbers in a dataset- which I imported as a .csv from a url, using rio's import()- using the code mean(dataset[398,5:24])

the mean() function returns the warning message:

Warning message: In mean.default(test1) : argument is not numeric or logical: returning NA'''

even though, when I type dataset[398,5:24] to check they are logical, R responds with the following:

          V5       V6       V7       V8       V9      V10
398 1.877356 1.849893 1.923246 1.809628 1.949854 2.028761

         V11      V12      V13      V14      V15      V16
398 1.952358 1.960568 2.010918 2.042482 2.051661 2.031455

         V17      V18      V19      V20      V21      V22
398 2.044637 1.985774 1.785322 1.853449 1.882113 1.816115

        V23      V24
398 1.79505 1.806201 '''

what can I do? I simply do not understand why it thinks the argument is not numeric or logical, or what I can do now. Any help would be much appreciated.

Upvotes: 0

Views: 80

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389325

dataset[398,5:24] is still a dataframe and mean expects a vector.

Consider example from mtcars built-in dataset.

mtcars[8, 3:8]

#           disp hp drat   wt qsec vs
#Merc 240D 146.7 62 3.69 3.19   20  1

mean(mtcars[8, 3:8])
#[1] NA

Warning message: In mean.default(mtcars[8, 3:8]) : argument is not numeric or logical: returning NA

You can unlist the data first to turn it into a vector and then use mean.

mean(unlist(mtcars[8, 3:8]))
#[1] 39.43

Add na.rm = TRUE if you have NA in your data. So in your case, it would be :

mean(unlist(dataset[398,5:24]), na.rm = TRUE)

Upvotes: 1

Related Questions