简体   繁体   中英

Join two data frames

I have two data frames:

  customer material Freq
1  1       12       1
2  1       10       1
3  1        8       1
4  1        4       1
5  1        3       1
6  1        2       1

and the second one:

  material class
1 12       A
2 10       B
3 3        C
4 4        D
5 5        E
6 6        F

Now I want to merge the two data frames. I tried it with:

e <- left_join(A, B, by="material")

But then I have all materials multiple times. How can I solve this problem?

You could try:

left_join(A, B %>% distinct(), by="material")

Here I presume that you have some duplicate values in B . With the data you provided the code runs fine; I cannot see any material mentioned multiple times.

Try this: You can reclass.

library(tidyverse)
#df1$material<-as.factor(df1$material)
#df2$material<-as.factor(df2$material)
#df2$class<-as.character(df2$class)
df1 %>% 
  left_join(df2,by="material")

If I understand the end result correctly then you could use base merge :

df3 <- merge(df1, df2, by = "material")

You can also use in pipes with :

df3 <- df1 %>% 
  merge(df2, by = "material")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM