Program Tip

데이터 프레임에서 열을 정렬하여 그룹 (사 분위수, 십 분위수 등)을 빠르게 형성하는 방법

programtip 2020. 11. 29. 12:11
반응형

데이터 프레임에서 열을 정렬하여 그룹 (사 분위수, 십 분위수 등)을 빠르게 형성하는 방법


나는 re ordersort. 벡터 또는 데이터 프레임을 그룹으로 분류하는 것이 있습니까 (사 분위수 또는 십 분위수)? "수동"솔루션이 있지만 그룹 테스트를 거친 더 나은 솔루션이있을 수 있습니다.

내 시도는 다음과 같습니다.

temp <- data.frame(name=letters[1:12], value=rnorm(12), quartile=rep(NA, 12))
temp
#    name       value quartile
# 1     a  2.55118169       NA
# 2     b  0.79755259       NA
# 3     c  0.16918905       NA
# 4     d  1.73359245       NA
# 5     e  0.41027113       NA
# 6     f  0.73012966       NA
# 7     g -1.35901658       NA
# 8     h -0.80591167       NA
# 9     i  0.48966739       NA
# 10    j  0.88856758       NA
# 11    k  0.05146856       NA
# 12    l -0.12310229       NA
temp.sorted <- temp[order(temp$value), ]
temp.sorted$quartile <- rep(1:4, each=12/4)
temp <- temp.sorted[order(as.numeric(rownames(temp.sorted))), ]
temp
#    name       value quartile
# 1     a  2.55118169        4
# 2     b  0.79755259        3
# 3     c  0.16918905        2
# 4     d  1.73359245        4
# 5     e  0.41027113        2
# 6     f  0.73012966        3
# 7     g -1.35901658        1
# 8     h -0.80591167        1
# 9     i  0.48966739        3
# 10    j  0.88856758        4
# 11    k  0.05146856        2
# 12    l -0.12310229        1

더 나은 (더 깔끔하고 / 빠른 / 한 줄) 접근 방식이 있습니까? 감사!


내가 사용하는 방법은 다음 중 하나입니다 Hmisc::cut2(value, g=4).

temp$quartile <- with(temp, cut(value, 
                                breaks=quantile(value, probs=seq(0,1, by=0.25), na.rm=TRUE), 
                                include.lowest=TRUE))

대안은 다음과 같습니다.

temp$quartile <- with(temp, factor(
                            findInterval( val, c(-Inf,
                               quantile(val, probs=c(0.25, .5, .75)), Inf) , na.rm=TRUE), 
                            labels=c("Q1","Q2","Q3","Q4")
      ))

첫 번째는 사 분위수에 값으로 레이블을 지정하는 부작용이 있습니다.이 값은 "좋은 것"이라고 생각합니다. 그러나 이것이 "좋은 것"이 아니거나 주석에서 제기 된 유효한 문제가 문제가 될 수 있습니다. 버전 2와 함께 labels=에서 사용 cut하거나 다음 줄을 코드에 추가 할 수 있습니다.

temp$quartile <- factor(temp$quartile, levels=c("1","2","3","4") )

또는 더 이상 요소가 아니라 숫자 형 벡터이지만 작동 방식이 더 빠르지 만 약간 더 모호합니다.

temp$quartile <- as.numeric(temp$quartile)

ntilepackage 에는 편리한 기능 이 있습니다 dplyr. 만들려는 * 타일 또는 "빈"의 수를 매우 쉽게 정의 할 수 있다는 점에서 유연합니다.

패키지를로드하고 (설치하지 않은 경우 먼저 설치) 사 분위수 열을 추가합니다.

library(dplyr)
temp$quartile <- ntile(temp$value, 4)  

또는 dplyr 구문을 사용하려는 경우 :

temp <- temp %>% mutate(quartile = ntile(value, 4))

두 경우의 결과는 다음과 같습니다.

temp
#   name       value quartile
#1     a -0.56047565        1
#2     b -0.23017749        2
#3     c  1.55870831        4
#4     d  0.07050839        2
#5     e  0.12928774        3
#6     f  1.71506499        4
#7     g  0.46091621        3
#8     h -1.26506123        1
#9     i -0.68685285        1
#10    j -0.44566197        2
#11    k  1.22408180        4
#12    l  0.35981383        3

데이터:

사전에 "사 분위수"열 set.seed을 만들고이를 사용하여 무작위 화를 재현 할 수 있도록 할 필요는 없습니다 .

set.seed(123)
temp <- data.frame(name=letters[1:12], value=rnorm(12))

나는 그것을 data.table인터넷 검색하는 다른 사람을 위해 버전을 추가 할 것입니다 (즉, @BondedDust의 솔루션 data.table이 약간 번역 되고 축소되었습니다).

library(data.table)
setDT(temp)
temp[ , quartile := cut(value,
                        breaks = quantile(value, probs = 0:4/4),
                        labels = 1:4, right = FALSE)]

내가했던 것보다 훨씬 낫다 (더 깨끗하고 빠르다 ).

temp[ , quartile := 
        as.factor(ifelse(value < quantile(value, .25), 1,
                         ifelse(value < quantile(value, .5), 2,
                                ifelse(value < quantile(value, .75), 3, 4))]

그러나이 접근 방식은 Quantile이 구별되어야합니다. 예를 들어 실패 할 것입니다 rep(0:1, c(100, 1)). 이 경우에 할 일은 개방형이므로 귀하에게 맡기십시오.


quantile()함수 를 사용할 수 있지만 사용할 때 반올림 / 정밀도를 처리해야합니다 cut(). 그래서

set.seed(123)
temp <- data.frame(name=letters[1:12], value=rnorm(12), quartile=rep(NA, 12))
brks <- with(temp, quantile(value, probs = c(0, 0.25, 0.5, 0.75, 1)))
temp <- within(temp, quartile <- cut(value, breaks = brks, labels = 1:4, 
                                     include.lowest = TRUE))

기부:

> head(temp)
  name       value quartile
1    a -0.56047565        1
2    b -0.23017749        2
3    c  1.55870831        4
4    d  0.07050839        2
5    e  0.12928774        3
6    f  1.71506499        4

적응 dplyr::ntile을 활용하는 data.table최적화하여 빠른 솔루션을 제공합니다.

library(data.table)
setDT(temp)
temp[order(value) , quartile := floor( 1 + 4 * (.I-1) / .N)]

아마도 더 깨끗한 것으로 간주되지는 않지만 더 빠르고 한 줄입니다.

더 큰 데이터 세트에 대한 타이밍

이 솔루션 비교 ntilecut대한 data.table@docendo_discimus 및 @MichaelChirico 제안한합니다.

library(microbenchmark)
library(dplyr)

set.seed(123)

n <- 1e6
temp <- data.frame(name=sample(letters, size=n, replace=TRUE), value=rnorm(n))
setDT(temp)

microbenchmark(
    "ntile" = temp[, quartile_ntile := ntile(value, 4)],
    "cut" = temp[, quartile_cut := cut(value,
                                       breaks = quantile(value, probs = seq(0, 1, by=1/4)),
                                       labels = 1:4, right=FALSE)],
    "dt_ntile" = temp[order(value), quartile_ntile_dt := floor( 1 + 4 * (.I-1)/.N)]
)

제공 :

Unit: milliseconds
     expr      min       lq     mean   median       uq      max neval
    ntile 608.1126 647.4994 670.3160 686.5103 691.4846 712.4267   100
      cut 369.5391 373.3457 375.0913 374.3107 376.5512 385.8142   100
 dt_ntile 117.5736 119.5802 124.5397 120.5043 124.5902 145.7894   100

파티에 늦어서 죄송합니다. cut2데이터에 대한 최대 / 최소를 모르고 그룹이 동일하게 커지기를 원했기 때문에 사용하여 하나의 라이너를 추가 하고 싶었습니다. 중복으로 표시된 문제에서 cut2에 대해 읽었습니다 (아래 링크).

library(Hmisc)   #For cut2
set.seed(123)    #To keep answers below identical to my random run

temp <- data.frame(name=letters[1:12], value=rnorm(12), quartile=rep(NA, 12))

temp$quartile <- as.numeric(cut2(temp$value, g=4))   #as.numeric to number the factors
temp$quartileBounds <- cut2(temp$value, g=4)

temp

결과:

> temp
   name       value quartile  quartileBounds
1     a -0.56047565        1 [-1.265,-0.446)
2     b -0.23017749        2 [-0.446, 0.129)
3     c  1.55870831        4 [ 1.224, 1.715]
4     d  0.07050839        2 [-0.446, 0.129)
5     e  0.12928774        3 [ 0.129, 1.224)
6     f  1.71506499        4 [ 1.224, 1.715]
7     g  0.46091621        3 [ 0.129, 1.224)
8     h -1.26506123        1 [-1.265,-0.446)
9     i -0.68685285        1 [-1.265,-0.446)
10    j -0.44566197        2 [-0.446, 0.129)
11    k  1.22408180        4 [ 1.224, 1.715]
12    l  0.35981383        3 [ 0.129, 1.224)

cut2에 대해 자세히 읽은 비슷한 문제


temp$quartile <- ceiling(sapply(temp$value,function(x) sum(x-temp$value>=0))/(length(temp$value)/4))

데이터 세트 quantile()의 breaks 옵션 cut()사용하는 데 많은 문제가 발생했기 때문에 더 견고 해 보이는 버전을 제안하고 싶습니다 . ntile기능을 사용하고 plyr있지만 ecdf입력으로 도 작동 합니다.

temp[, `:=`(quartile = .bincode(x = ntile(value, 100), breaks = seq(0,100,25), right = TRUE, include.lowest = TRUE)
            decile = .bincode(x = ntile(value, 100), breaks = seq(0,100,10), right = TRUE, include.lowest = TRUE)
)]

temp[, `:=`(quartile = .bincode(x = ecdf(value)(value), breaks = seq(0,1,0.25), right = TRUE, include.lowest = TRUE)
            decile = .bincode(x = ecdf(value)(value), breaks = seq(0,1,0.1), right = TRUE, include.lowest = TRUE)
)]

그 맞습니까?


Try this function

getQuantileGroupNum <- function(vec, group_num, decreasing=FALSE) {
  if(decreasing) {
    abs(cut(vec, quantile(vec, probs=seq(0, 1, 1 / group_num), type=8, na.rm=TRUE), labels=FALSE, include.lowest=T) - group_num - 1)
  } else {
    cut(vec, quantile(vec, probs=seq(0, 1, 1 / group_num), type=8, na.rm=TRUE), labels=FALSE, include.lowest=T)
  }
}
> t1 <- runif(7)
> t1
[1] 0.4336094 0.2842928 0.5578876 0.2678694 0.6495285 0.3706474 0.5976223
> getQuantileGroupNum(t1, 4)
[1] 2 1 3 1 4 2 4
> getQuantileGroupNum(t1, 4, decreasing=T)
[1] 3 4 2 4 1 3 1

There is possibly a quicker way, but I would do:

a <- rnorm(100) # Our data
q <- quantile(a) # You can supply your own breaks, see ?quantile

# Define a simple function that checks in which quantile a number falls
getQuant <- function(x)
   {
   for (i in 1:(length(q)-1))
       {
       if (x>=q[i] && x<q[i+1])
          break;
       }
   i
   }

# Apply the function to the data
res <- unlist(lapply(as.matrix(a), getQuant))

참고URL : https://stackoverflow.com/questions/4126326/how-to-quickly-form-groups-quartiles-deciles-etc-by-ordering-columns-in-a

반응형