0

I have the following two test dfs:

df1 <- data.frame(block = c('1' , '1' , '1' , '2' , '2', '2' , '3' , '3' , '3') ,
                 type = c('a' , 'b' , 'c' , 'b' , 'a' , 'c' , 'c' , 'b' , 'a') ,
                 number = c('1' , '3' , '6' , '2' , '3' , '4' , '5' , '1' , '3'))


df2 <- data.frame(block = c('1' , '1' , '1' , '2' , '2', '2' , '3' , '3' , '3') ,
                  type = c('b' , 'c' , 'a' , 'c' , 'a' , 'b' , 'a' , 'c' , 'b') ,
                  value = c('3' , '2' , '3' , '5' , '1' , '6' , '3' , '2' , '1'))

I'd like to reorder the "value" column from df2 by the "type" column from df1. Then I'd like to merge the two dfs using cbind or similar and remove the extra "block" column in the output.

The output would look like:

df3 <- data.frame(block = c('1' , '1' , '1' , '2' , '2', '2' , '3' , '3' , '3') ,
                  type = c('a' , 'b' , 'c' , 'b' , 'a' , 'c' , 'c' , 'b' , 'a') ,
                  number = c('1' , '3' , '6' , '2' , '3' , '4' , '5' , '1' , '3') , 
                  value = c('3' , '3' , '2' , '6' , '1' , '5' , '2' , '1' , '3'))

A tidy verse method is preferred.

davidr21
  • 121
  • 3

2 Answers2

0
  • We can try
merge(df1 , df2)

  block type number value
1     1    a      1     3
2     1    b      3     3
3     1    c      6     2
4     2    a      3     1
5     2    b      2     6
6     2    c      4     5
7     3    a      3     3
8     3    b      1     1
9     3    c      5     2
Mohamed Desouky
  • 4,340
  • 2
  • 4
  • 19
0
result = df1 %>% left_join(df2)
identical(df3, result)
# [1] TRUE

If you want an explicit row ordering in there, put %>% arrange(block, type) after the left_join().

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294