2017-09-22 1 views
0

20 개의 변수와 400,000 개의 인스턴스가있는 데이터 프레임이 있습니다. 모든 변수는 평균 0과 표준 편차 1로 정규화됩니다. 각 변수의 각 인스턴스를 quantile으로 분류 할 수있는 함수를 작성하고 싶습니다. 미리정규화 된 벡터가 양자점 (예 : 0, 0.25, 0.5, 0.75,1)으로 데이터 프레임의 각 인스턴스를 식별하는 방법은 무엇입니까?

Lets say we have a normalized vector 
a <- c(0.2132821 -1.5136988 0.6450274 1.5085178 0.2132821 1.5085178 0.6450274) 

And the quantiles for this vector are 
quant.a <- c(-1.5136988 -1.0819535 0.2132821 1.0767726 1.5085178) 

where -1.5136988 is 0% 
     -1.0819535 is 25% 
     0.2132821 is 50% 
     1.0767726 is 75% 
     1.5085178 is 100% (all are elements in vector 'quant.a') 

Now, I want to classify each element of vector 'a' as follows 
new.a <- c(0.5, 0, 0.75, 1, 0.5, 1, 0.75) 

You can use the following code to workout through the example as it is not possible for me to share the actual data 

# Generate random data 
set.seed(99) 

# All variables are on a scale of 1-9 
a <- floor(runif(500, min = 1, max = 9)) 
b <- floor(runif(500, min = 1, max = 9)) 
c <- floor(runif(500, min = 1, max = 9)) 

# store variables as dataframe 
x <- data.frame(cbind(a,b,c)) 

#Scale variables 
scaled.dat <- data.frame(scale(x)) 

# check that we get mean of 0 and sd of 1 
colMeans(scaled.dat) 
apply(scaled.dat, 2, sd) 

# generate quantiles for each variables 
quantiles <- data.frame(apply(scaled.dat,2,quantile)) 

감사

답변

1
library(dplyr) 
yourdataframe %>% 
    mutate_all(funs(ntile(., 4)/4) 
+0

헤이 브라이언! 그 ith quantile (quantile 1, quantile 2, ... 등등)을 찾는 좋은 방법. 하지만 나는 출력이 (0, .25, .5, .75, 1)이되도록 찾고 있었다. 하지만 어쨌든 고맙습니다. 새로운 물건을 배우는 것이 항상 좋다. – Nikhil

+0

@Nikhil, 당신은 그 표현을 얻기 위해 단지'/ 4'를 포함해야합니다. 보다 명확한 라벨링을 원할 경우, 대신에'percent_rank'를 사용하고'mutate_all (funs (cut (., 0 : 4/4))) '에 대한 또 다른 호출을 사용할 수 있습니다. – Brian

+0

정말 고마워요! 그것은 훌륭하게 작동했습니다 !!! – Nikhil

2
a <- c(0.2132821, -1.5136988, 0.6450274 , 1.5085178 , 0.2132821 , 1.5085178 , 0.6450274) 

quant.a = quantile(a) 

aux_matrix = findInterval(a, quant.a) 

new.a = ifelse(aux_matrix == 1|aux_matrix == 0, 0, 
       ifelse(aux_matrix == 2, 0.5, 
         ifelse(aux_matrix==3,0.75, 
          1))) 

print(new.a) 

0.50 0.00 0.75 1.00 0.50 1.00 0.75 
+0

'findInterval 온도 = (a, quant.a); as.numeric (gsub ("%", "", 이름 (quant.a) [ifelse (temp == 1, 1, pmin (length (quant.a), temp + 1)))))/100' –

+0

감사합니다 Alexey !! 내가 의도 한대로 완벽하게 작동합니다. – Nikhil

+0

안녕 d.b! 너를 시험해 보았다. 그것 1 quantile에 의해 떨어져 아직도. .25 대신 내 데이터 프레임에서 .5를 제공합니다. 하지만 그 원인을 파악하려고 노력할 것입니다. 그리고 당신의 도움에 감사드립니다. – Nikhil

관련 문제