2

So I have this vector:

x
 [1] 76 89 78 50 84 56 29 53 32 68
112 Levels: 0 1 10 100 101 102 103 104 105 106 107 108 109 11 110 12 13 ... eta

why this happens?

[1] NA
Warning message:
In mean.default(x) : l'argomento non è numerico o logico: restituisco NA
user3083324
  • 585
  • 8
  • 23
  • 1
    Trying to translate the error message: "the argument is neither numerical nor logical. Replaced with N/A". – Floris Dec 09 '13 at 17:45
  • 1
    You can set the language to English using [this](http://stackoverflow.com/questions/13575180/how-to-change-the-language-of-errors-in-r) – agstudy Dec 09 '13 at 17:52

3 Answers3

7

It looks like x is a factor. There is a gotcha when converting factors to numbers. You need to use:

mean(as.numeric(as.character(x)), na.rm=TRUE)

If you don't convert to character first, you will get the underlying factor codes.

James
  • 65,548
  • 14
  • 155
  • 193
0

Looks like x is a categorical variable -- try

mean(as.numeric(as.character(x)))

(as per James pointing out that without as.character, you get factor codes:

x <- as.factor(10:20)
as.numeric(x)
[1]  1  2  3  4  5  6  7  8  9 10 11

Leaving out na.rm=TRUE since, while safer, it wasn't causing the problem)

colcarroll
  • 3,632
  • 17
  • 25
  • 1
    Thanks! How do I know if I'm dealing with categorical or numerical variables? – user3083324 Dec 09 '13 at 17:46
  • 1
    What gave it away was that printing `x` gave you levels. `R` usually parses "numberish" things into numerical variables, but I would guess that this vector was sliced a bit to get rid of some of them. If you inspect the original vector, I bet you'd find something that isn't "numberish". – colcarroll Dec 09 '13 at 17:49
  • Use `str(your_object)` to see what mode things are stored in. – Bryan Hanson Dec 09 '13 at 17:54
  • Indeed I thought that something not "numberish" might be hiding on the dataset but I have no clue how to locate it. – user3083324 Dec 09 '13 at 21:25
  • Haven't seen your data set, but you can play around with `> test <- as.data.frame(c(1:10, "foo"))`, which will load the one column as a categorical variable. Even once you get rid of the last row (`test[,1:10]`), it will remain categorical. – colcarroll Dec 09 '13 at 21:44
  • I'm wondering if there's an easy way to locate non numeric data in a huge vector. Anyway thx for the help! – user3083324 Dec 09 '13 at 23:19
  • Try `x[is.na(as.numeric(x))]`. – colcarroll Dec 10 '13 at 00:16
0

In addition to changing to numeric values, when you use the mean function, make sure you specify na.rm=TRUE in case you have NA values in the vector. Otherwise, it shows the warning you saw.

alittleboy
  • 10,616
  • 23
  • 67
  • 107