Programing

두 개의 열을 기반으로 두 개의 데이터 프레임을 결합하는 방법은 무엇입니까?

lottogame 2020. 8. 28. 07:49
반응형

두 개의 열을 기반으로 두 개의 데이터 프레임을 결합하는 방법은 무엇입니까? [복제]


을 (를) 사용 plyr하여 데이터 프레임을 결합 할 수 있다는 것을 알고 merge있지만 지금까지 두 개의 데이터 프레임을 2 개의 열을 기반으로하는 여러 열과 병합하는 방법을 모릅니다.


에 대한 설명서를 참조하십시오 ?merge.

By default the data frames are merged on the columns with names they both have, 
 but separate specifications of the columns can be given by by.x and by.y.

이것은 merge둘 이상의 열을 기반으로 데이터 프레임을 병합 한다는 것을 분명히 의미합니다 . 문서에 제공된 최종 예에서 :

x <- data.frame(k1=c(NA,NA,3,4,5), k2=c(1,NA,NA,4,5), data=1:5)
y <- data.frame(k1=c(NA,2,NA,4,5), k2=c(NA,NA,3,4,5), data=1:5)
merge(x, y, by=c("k1","k2")) # NA's match

이 예는의 사용을 보여주기위한 incomparables것이지만 여러 열을 사용한 병합도 보여줍니다 . 또한 각각 별도의 열을 지정할 수 있습니다 xy사용 by.xby.y.


도움이 되었기를 바랍니다;

df1 = data.frame(CustomerId=c(1:10),
             Hobby = c(rep("sing", 4), rep("pingpong", 3), rep("hiking", 3)),
             Product=c(rep("Toaster",3),rep("Phone", 2), rep("Radio",3), rep("Stereo", 2)))

df2 = data.frame(CustomerId=c(2,4,6, 8, 10),State=c(rep("Alabama",2),rep("Ohio",1),   rep("Cal", 2)),
             like=c("sing", 'hiking', "pingpong", 'hiking', "sing"))

df3 = merge(df1, df2, by.x=c("CustomerId", "Hobby"), by.y=c("CustomerId", "like"))

같은 것을 가정 df1$Hobby하고 df2$like의미합니다.


join 명령 (dplyr)을 사용할 수도 있습니다.

예를 들면 :

new_dataset <- dataset1 %>% right_join(dataset2, by=c("column1","column2"))

참고 URL : https://stackoverflow.com/questions/6709151/how-do-i-combine-two-data-frames-based-on-two-columns

반응형