Calculation of the mode for nominal as well as continuous variables in [R]

Can anyone help me with this?

If I run:

> mode(iris$Species)
[1] "numeric"
> mode(iris$Sepal.Width)
[1] "numeric"

Then I get "numeric"as an answer

Greetings

M

+3
source share
2 answers

see ?mode: modeprovides you with a storage mode. If you need a value with the maximum quantity, use the table.

> Sample <- sample(letters[1:5],50,replace=T)
> tmp <- table(Sample)
> tmp
Sample
 a  b  c  d  e 
 9 12  9  7 13 
> tmp[which(tmp==max(tmp))]
 e 
13 

Please read the help files if the function does not do what you think.

A few additional explanations:

max(tmp) - this is maximum tmp

tmp == max(tmp) gives a logical vector with a length of tmp, indicating whether or not the value of max (tmp) is equal.

which(tmp == max(tmp))returns an index of values ​​in a vector TRUE. You use these indices to select the value in tmp, which is the maximum value.

?which, ?max R.

+2

mode() , "numeric". "" , .. . . ?mode , R .

:

> set.seed(1) ## reproducible example
> dat <- sample(1:5, 100, replace = TRUE) ## dummy data
> (tab <- table(dat)) ## tabulate the frequencies
dat
 1  2  3  4  5 
13 25 19 26 17 
> which.max(tab) ## which is the mode?
4 
4 
> tab[which.max(tab)] ## what is the frequency of the mode?
 4 
26

- , (PDF) . , PDF, .

, :

> sepalwd <- with(iris, density(Sepal.Width)) ## kernel density estimate
> plot(sepalwd)
> str(sepalwd)
List of 7
 $ x        : num [1:512] 1.63 1.64 1.64 1.65 1.65 ...
 $ y        : num [1:512] 0.000244 0.000283 0.000329 0.000379 0.000436 ...
 $ bw       : num 0.123
 $ n        : int 150
 $ call     : language density.default(x = Sepal.Width)
 $ data.name: chr "Sepal.Width"
 $ has.na   : logi FALSE
 - attr(*, "class")= chr "density"
> with(sepalwd, which.max(y)) ## which value has maximal density?
[1] 224
> with(sepalwd, x[which.max(y)]) ## use the above to find the mode
[1] 3.000314

. ?density. density() n = 512 . , :

> sepalwd2 <- with(iris, density(Sepal.Width, n = 2048))
> with(sepalwd, x[which.max(y)])
[1] 3.000314

.

+8

Source: https://habr.com/ru/post/1792501/


All Articles