짓궂군요 () '와' 에서 'R', '이 있는 표준 함수 (), d # 39 마드얀의 you& 뭘 기대하고 있다. '모드 ()' 이 아닌 값을 알려줍니다 내부 저장 모드 객체에는 발생하는 가장 최근 인수. 하지만 그 안에는 는 표준 라이브러리 함수를 구현하는 통계 모드를 벡터 (또는 목록)?
한 번 더 사용할 수 있는 솔루션을 모두 숫자 &. character/factor 데이터:
Mode <- function(x) {
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}
&Amp 생성할 수 있는 시스템에 대한 나의 작은 리틀이에요. 모드 찾습니다찾기 10m 정수 벡터입니다 반단면 약 두 번째.
데이터 세트의 경우 발생할 수 있다 '는', 그리고 여러 모드, 위의 솔루션이므로 외곽진입 which.막스 동일한 값을 첫 출연 되돌려줍니다 세트의 모드. , 모드를 사용하여 모든 반환되기를 이 변형 () 의 @digEmAll 정보를):
Modes <- function(x) {
ux <- unique(x)
tab <- tabulate(match(x, ux))
ux[tab == max(tab)]
}
이 모드를 제공하는 패키지 '는' 좁히어 모지스트 추정기 일도량 단봉 (때로는 다중 모드) 의 일반 모드 데이터 및 값프로필 확률 측도.
mySamples <- c(19, 4, 5, 7, 29, 19, 29, 13, 25, 19)
library(modeest)
mlv(mySamples, method = "mfv")
Mode (most likely value): 19
Bickel's modal skewness: -0.1
Call: mlv.default(x = mySamples, method = "mfv")
자세한 내용은 이 페이지
그리고 더럽고 빠른 길을 찾는 따라오렴 ᄀ군의 숫자를 추정 모드를 통해 연속 일도량 분포 (예를 들어 정규분포) 는 다음과 같은 함수 정의 및 사용.
estimate_mode <- function(x) {
d <- density(x)
d$x[which.max(d$y)]
}
그 다음에는 내려받습니다 모드 추정치입니다:
x <- c(5.8, 5.6, 6.2, 4.1, 4.9, 2.4, 3.9, 1.8, 5.7, 3.2)
estimate_mode(x)
## 5.439788
다음 세 가지 형식으로 완료되니라 함수은.
방법 = " mode"; [기본]: 다른 벡터, NA 을 반환하는지 단봉 모드를 계산합니다. 방법 = nmodes" ";: vector 의 수를 계산하는 모드 방법 = modes" ";: 모든 모드 또는 폴리모달 열거합니다 단봉 대한 벡터
modeav <- function (x, method = "mode", na.rm = FALSE)
{
x <- unlist(x)
if (na.rm)
x <- x[!is.na(x)]
u <- unique(x)
n <- length(u)
#get frequencies of each of the unique values in the vector
frequencies <- rep(0, n)
for (i in seq_len(n)) {
if (is.na(u[i])) {
frequencies[i] <- sum(is.na(x))
}
else {
frequencies[i] <- sum(x == u[i], na.rm = TRUE)
}
}
#mode if a unimodal vector, else NA
if (method == "mode" | is.na(method) | method == "")
{return(ifelse(length(frequencies[frequencies==max(frequencies)])>1,NA,u[which.max(frequencies)]))}
#number of modes
if(method == "nmode" | method == "nmodes")
{return(length(frequencies[frequencies==max(frequencies)]))}
#list of all modes
if (method == "modes" | method == "modevalues")
{return(u[which(frequencies==max(frequencies), arr.ind = FALSE, useNames = FALSE)])}
#error trap the method
warning("Warning: method not recognised. Valid methods are 'mode' [default], 'nmodes' and 'modes'")
return()
}
그러나 꼭 이래야겠어요 수정할 수 있는 분배란 예를 들어 이리저리 좀 콘트레인 값만 0 과 1 사이의.
estimate_mode <- function(x,from=min(x), to=max(x)) {
d <- density(x, from=from, to=to)
d$x[which.max(d$y)]
}
우리는 전혀 알고 싶지 않은 constrain 너회의 분배란 충스러웠으니 = - =;;; 대량량 NUMBER" 위해 설정한 후 " " 대량량 NUMBER".
이 질문에 대한 답을 사용자의 이름과 달리 의존하고 있는 유지보수합니다 () ',' x '의 데이터 유형은 반환되었습니다 value (s).
stat_mode <- function(x, return_multiple = TRUE, na.rm = FALSE) {
if(na.rm){
x <- na.omit(x)
}
ux <- unique(x)
freq <- tabulate(match(x, ux))
mode_loc <- if(return_multiple) which(freq==max(freq)) else which.max(freq)
return(ux[mode_loc])
}
옵션으로 작동하잖아 표시하십시오 유지보수합니다 params) 및 데이터 형식:
foo <- c(2L, 2L, 3L, 4L, 4L, 5L, NA, NA)
bar <- c('mouse','mouse','dog','cat','cat','bird',NA,NA)
str(stat_mode(foo)) # int [1:3] 2 4 NA
str(stat_mode(bar)) # chr [1:3] "mouse" "cat" NA
str(stat_mode(bar, na.rm=T)) # chr [1:2] "mouse" "cat"
str(stat_mode(bar, return_mult=F, na.rm=T)) # chr "mouse"
덕분에 대한 @Frank 단순화.
MODE <- function(dataframe){
DF <- as.data.frame(dataframe)
MODE2 <- function(x){
if (is.numeric(x) == FALSE){
df <- as.data.frame(table(x))
df <- df[order(df$Freq), ]
m <- max(df$Freq)
MODE1 <- as.vector(as.character(subset(df, Freq == m)[, 1]))
if (sum(df$Freq)/length(df$Freq)==1){
warning("No Mode: Frequency of all values is 1", call. = FALSE)
}else{
return(MODE1)
}
}else{
df <- as.data.frame(table(x))
df <- df[order(df$Freq), ]
m <- max(df$Freq)
MODE1 <- as.vector(as.numeric(as.character(subset(df, Freq == m)[, 1])))
if (sum(df$Freq)/length(df$Freq)==1){
warning("No Mode: Frequency of all values is 1", call. = FALSE)
}else{
return(MODE1)
}
}
}
return(as.vector(lapply(DF, MODE2)))
}
MODE(mtcars)
MODE(CO2)
MODE(ToothGrowth)
MODE(InsectSprays)
Mode <- function(x, method = "one", na.rm = FALSE) {
x <- unlist(x)
if (na.rm) {
x <- x[!is.na(x)]
}
# Get unique values
ux <- unique(x)
n <- length(ux)
# Get frequencies of all unique values
frequencies <- tabulate(match(x, ux))
modes <- frequencies == max(frequencies)
# Determine number of modes
nmodes <- sum(modes)
nmodes <- ifelse(nmodes==n, 0L, nmodes)
if (method %in% c("one", "mode", "") | is.na(method)) {
# Return NA if not exactly one mode, else return the mode
if (nmodes != 1) {
return(NA)
} else {
return(ux[which(modes)])
}
} else if (method %in% c("n", "nmodes")) {
# Return the number of modes
return(nmodes)
} else if (method %in% c("all", "modes")) {
# Return NA if no modes exist, else return all modes
if (nmodes > 0) {
return(ux[which(modes)])
} else {
return(NA)
}
}
warning("Warning: method not recognised. Valid methods are 'one'/'mode' [default], 'n'/'nmodes' and 'all'/'modes'")
}
이것은 함수 com/go/downloads_kr 모드.
mode <- function(x) {
unique_val <- unique(x)
counts <- vector()
for (i in 1:length(unique_val)) {
counts[i] <- length(which(x==unique_val[i]))
}
position <- c(which(counts==max(counts)))
if (mean(counts)==max(counts))
mode_x <- 'Mode does not exist'
else
mode_x <- unique_val[position]
return(mode_x)
}
R 은 정말 많은 것을 제공할 뿐만 아니라 추가 패키지 중 일부는 [통계] 모드 번호 목록 / 시리즈 / 벡터.
그러나 표준 라이브러리 자체가 # 39, t R 의 doesn& 내장현 메서드로부터 보유하는 것으로 보인다. 이를 해결할 수 있는 방법 중 하나는 chunghwa 사용하여 다음과 같은 일부 (이 경우 자주 사용하는 기능을 및 선반가공.):
mySamples <- c(19, 4, 5, 7, 29, 19, 29, 13, 25, 19)
tabSmpl<-tabulate(mySamples)
SmplMode<-which(tabSmpl== max(tabSmpl))
if(sum(tabSmpl == max(tabSmpl))>1) SmplMode<-NA
> SmplMode
[1] 19
목록, 임시 변수를 사용하는 대형 샘플링합니다 고려해야 합니다 max (트래비스마플) 값 (R, t 알게 될 것 "이라며" 내가 don& 자동으로 최적화합니다 # 39 이)
참조: 지켜보리니 ", 어때, 마드얀의 " 및 모드? 이 R 과 킥 스타팅 < br>; 이 사실을 확인할 수 있을 것으로 보인다 (이 중 적어도 vmware. 이 강의), isn& # 39 는 모드 기능을 ᄅ씨 (음. 모드 () 를 사용할 수 있다는 com/go/4e6b330a_kr 유형을 주장했다).
이를 위해 여러 가지 솔루션을 제공하는 하나. 그리고 그 이후로 나는 내 자신의 첫 번째 점검됩니다 썼다. 여기에 글이 도움이 된다면, 누구나:
Mode <- function(x){
y <- data.frame(table(x))
y[y$Freq == max(y$Freq),1]
}
몇 가지 예를 통해 it 를 테스트할 수 있습니다. 나는 '아이리스' 등의 데이터 세트. 숫자 데이터 수 있는 테스트
> Mode(iris$Sepal.Length)
[1] 5
확인할 수 있는 올바릅니다.
이제 필드에 아이리스 데이터세트를 없는 유일한 비사양 숫자 (종) 모드. # 39 의 예를 통해 let& 자체 테스트
> test <- c("red","red","green","blue","red")
> Mode(test)
[1] red
주석이 언급한 보존해야 할 수 있는 사용자 입력 유형:. 이 경우 모드 기능을 수정할 수 있습니다.
Mode <- function(x){
y <- data.frame(table(x))
z <- y[y$Freq == max(y$Freq),1]
as(as.character(z),class(x))
}
마지막 줄의 마지막 값을 유형에 따라 원래 입력 함수는 단순히 강제 변환 모드.
Mode <- function(v) {
# checking unique numbers in the input
uniqv <- unique(v)
# frquency of most occured value in the input data
m1 <- max(tabulate(match(v, uniqv)))
n <- length(tabulate(match(v, uniqv)))
# if all elements are same
same_val_check <- all(diff(v) == 0)
if(same_val_check == F){
# frquency of second most occured value in the input data
m2 <- sort(tabulate(match(v, uniqv)),partial=n-1)[n-1]
if (m1 != m2) {
# Returning the most repeated value
mode <- uniqv[which.max(tabulate(match(v, uniqv)))]
} else{
mode <- "Two or more values have same frequency. So mode can't be calculated."
}
} else {
# if all elements are same
mode <- unique(v)
}
return(mode)
}
출력,
x1 <- c(1,2,3,3,3,4,5)
Mode(x1)
# [1] 3
x2 <- c(1,2,3,4,5)
Mode(x2)
# [1] "Two or more varibles have same frequency. So mode can't be calculated."
x3 <- c(1,1,2,3,3,4,5)
Mode(x3)
# [1] "Two or more values have same frequency. So mode can't be calculated."
Mode <- function(x) {
if ( length(x) <= 2 ) return(x[1])
if ( anyNA(x) ) x = x[!is.na(x)]
ux <- unique(x)
ux[which.max(tabulate(match(x, ux)))]
}