1

i have a table say,Table A :

uid pid code
1     1  aaa
2     1  ccc
3     4  ddd 
4     2  eee

i have another table, Table B:

pid msg
1   good
2   inspiring
3   thing to wtch
4   terrible

now, i want to replace pid in table A with msg in Table B.

I used merge(tableA, tableb, by =c("pid"))

I got the result as

uid pid code msg
1    1  aaa  good
2    1  ccc  good
3    4  ddd  terrible
4    2  eee  inspiring

where in i want the result as

uid msg code
1   good aaa
2   good ccc
3   terrible ddd
4   inspiring eee
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
Prajna
  • 129
  • 1
  • 8

2 Answers2

2

Your approach seems absolutely correct, just needs further steps:

  1. selection of required columns
  2. reordering them

With tidyverse functions, you can do something like:

TableA %>%
  left_join(TableB) %>%
  select(uid, msg, code)

which gives:

  uid       msg code
1   1      good  aaa
2   2      good  ccc
3   3  terrible  ddd
4   4 inspiring  eee
Aramis7d
  • 2,444
  • 19
  • 25
0

Base R solution:

newtable = merge(tableA,tableB,by = "pid")
newtable$pid = NULL
newtable = newtable[order(newtable$uid,decreasing=FALSE),c(1,3,2)]
tushaR
  • 3,083
  • 1
  • 20
  • 33