2014-08-31 6 views
2

기본적으로 데이터 프레임에서 중복 된 데이터를 삭제하고 두 개의 열 (이름 및 클러스터)별로 그룹화 된 열의 가장 낮은 값을 유지하려고합니다. 여기 내 dataframe 경우 예를 들어, :groupby 및 r 데이터 프레임에서 가장 낮은 값 제거

 Name cluster score 
19  Steve a1  30 
51  Steve a2  30 
83  Steve a2  -28 
93  Steve a2  -38 
115 Bob  a4  30 
147 Bob  a5  -8 
179 Bob  a5  30 

팬더와 SQL이는 GROUPBY 수행 할 것입니다하지만 난 R에서 그것을 알아 내기 위해 사투를 벌인거야 정말조차 시작. 이름과 클러스터의 이중 정렬을 시도했습니다. 첫 번째 groupby는 Name이고 cluster입니다. 그래서 3 개의 'Steve, a2'가 있기 때문에 가장 낮은 점수를 지키고 싶습니다.

 Name cluster score 
19  Steve a1  30 
93  Steve a2  -38 
115 Bob  a4  30 
147 Bob  a5  -8 

어떤 도움이

답변

2

을 여기

library(dplyr) 


Name=c("Steve", "Steve", "Steve", "Steve", "Bob", "Bob", "Bob") 
cluster=c("a1", "a2", "a2", "a2", "a4", "a5", "a5") 
score=c(30,30,-28,-38,30,-8,30) 
yourdf<-data.frame(Name,cluster,score) 

yourdf %>% 
    group_by(Name,cluster) %>% 
    filter(score == min(score)) 

    Name cluster score 
1 Steve  a1 30 
2 Steve  a2 -38 
3 Bob  a4 30 
4 Bob  a5 -8 
1

를 작동하는 기본 R의 접근 방식을 크게 감상 할 수있다 :

# Read in sample data 
df<-read.table(text=" 
     Name cluster score 
19  Steve a1  30 
51  Steve a2  30 
83  Steve a2  -28 
93  Steve a2  -38 
115 Bob  a4  30 
147 Bob  a5  -8 
179 Bob  a5  30", header=TRUE) 

# order it 
df_sorted <- df[with(df, order(Name, cluster, score)),] 

# get rid of duplicated names and clusters, keeping the first, 
# which will be the minimum score due to the sorting. 

df_sorted[!duplicated(df_sorted[,c('Name','cluster')]), ] 
#  Name cluster score 
#115 Bob  a4 30 
#147 Bob  a5 -8 
#19 Steve  a1 30 
#93 Steve  a2 -38 

내 원하는 출력은 다음이 될 것입니다

2

그리고 간단한 data.table 솔루션은

library(data.table) 
setDT(df)[, list(score = score[which.min(score)]), by = list(Name, cluster)] 
#  Name cluster score 
# 1: Steve  a1 30 
# 2: Steve  a2 -38 
# 3: Bob  a4 30 
# 4: Bob  a5 -8 
2

aggregate에 적합합니다.

> aggregate(score ~ Name + cluster, mydf, min) 
# Name cluster score 
# 1 Steve  a1 30 
# 2 Steve  a2 -38 
# 3 Bob  a4 30 
# 4 Bob  a5 -8 

여기에서 mydf은 원본 데이터입니다.

관련 문제