2017-12-07 20 views
0

"내 첫 번째 항목"테이블에 "tech_distance"테이블을 포함하고 싶습니다. 두 개의 데이터 테이블 :두 개의 데이터 테이블 일치 (Vlookup, dplyr, match(), left_join) 행 수 유지

head(first_occurrences) 
    Main year Second occurrence tech_distance 
1 A01B 2004 E21B   1   0.7 
2 A01B 2004 E21B   1   0.5 
3 A01B 2004 E21B   1   0.7 
4 A01B 2004 E21B   1   0.5 
5 A01B 2004 E21B   1   0.5 
6 A01B 2004 E21B   1   1.0 

내가 사용하는 한 개의 mutate을 dplyr에 :

head(first_occurrences) 
# A tibble: 6 x 4 
# Groups: Main, Second [6] 
    year Main Second occurrence 
    <int> <chr> <chr>  <int> 
1 1991 C09D C08F   1 
2 2002 A47C A47D   1 
3 2002 G10K H05K   1 
4 2004 G06G C07K   1 
5 2015 B64F B64D   1 
6 2015 H02G B29C   1 


head(tech_distance) 
# A tibble: 6 x 2 
    Main tech_distance 
    <fctr>   <dbl> 
1 C09D   0.3 
2 A47C   0.0 
3 G10K   0.5 
4 G06G   0.5 
5 B64F   0.0 
6 H02G   0.5 

이것은 내가 얻고 싶은 결과이다

first_occurrences <- data %>% 
select(year = X3,Main = X7,Second = X8) %>% 
group_by(Main,Second) %>% 
mutate(occurrence = n(), tech_distance) %>% 
filter(occurrence >= 0, occurrence <= 1, !(Main == Second)) 

그러나 나는이 오류가 :

Error in mutate_impl(.data, dots) : 
Column `tech_distance` must be length 24 (the group size) or one, not 2 

그래서 병합()를 사용하여 시도 :

first_occurrences <- merge(first_occurrences, tech_distance, by.x = "Main", by.y = "Main", all.x=T) 

이 작동하는 것 같다을하지만, 데이터 세트 이전에있는 동안 나는 행 엄청난 수 (240,217 개 항목)

str(first_occurrences) 
'data.frame': 240217 obs. of 5 variables: 
    $ Main   : chr "A01B" "A01B" "A01B" "A01B" ... 
    $ year   : int 2004 2004 2004 2004 2004 2004 2004 2004 2004 2004 ... 
    $ Second  : chr "E21B" "E21B" "E21B" "E21B" ... 
    $ occurrence : int 1 1 1 1 1 1 1 1 1 1 ... 
    $ tech_distance: num 0.7 0.5 0.7 0.5 0.5 1 0.5 0.7 0.3 0 ... 

를 얻을 :

str(first_occurrences) 
Classes ‘grouped_df’, ‘tbl_df’, ‘tbl’ and 'data.frame': 8015 obs. of 4 variables: 
$ year  : int 1991 2002 2002 2004 2015 2015 2015 2015 2015 2015 ... 
$ Main  : chr "C09D" "A47C" "G10K" "G06G" ... 
$ Second : chr "C08F" "A47D" "H05K" "C07K" ... 
$ occurrence: int 1 1 1 1 1 1 1 1 1 1 ... 

str(tech_distance) 
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 8015 obs. of 2 variables: 
$ Main   : Factor w/ 815 levels "A01B","A01C",..: 345 62 684 651 265 749 328 735 173 788 ... 
$ tech_distance: num 0.3 0 0.5 0.5 0 0.5 0.5 0 0.5 0.5 ... 

아무도 같은 수의 행을 유지하는 두 개의 데이터 프레임을 병합하는 방법에 대해 알고 있습니까?

답변

0

Main 열은 모두 고유합니까? 일치하면 1 : 1 일치를 얻을 수 있으며 결과에는 8015 개의 행이 있습니다. 중복이 있으면 일대 다 일치를 얻고 더 많은 행을 얻습니다.

+0

:) 고유하지는 않습니다.이 경우 어떻게해야합니까? – Amleto

+0

@Amleto '고유'기능으로 고유하게 만들 수 있습니다. 그런 다음 데이터를 변경하거나 일대 다 조인을 수행하면됩니다. – Highland