0

Suppose these two tables - A and B

table A is

id v1  
1  10
3  20
5  20
6  15

table B is

id v2  
1  200
2  300
3  200
4  250
5  190
6  290

I want to add "v2" of B to A with the same "id" as follows:

table A should be

id v1 v2
1  10 200
3  20 200
5  20 190
6  15 290

I appreciate your help!

POTENZA
  • 1,377
  • 3
  • 17
  • 20
  • Any particular reason for not using "merge"? Just curious – vonbrand Feb 10 '13 at 00:13
  • My table is a sequence object created by TraMineR. When I merged my table with a regular data frame, I found my sequence table is corrupted if my understanding is correct. So I am trying to simply add a new column . – POTENZA Feb 10 '13 at 00:20

3 Answers3

2

Using data.table which is based on X[Y] syntax:

require(data.table)
dt1 <- data.table(df1)
dt2 <- data.table(df2)
setkey(dt1, "id")
setkey(dt2, "id")
> dt2[dt1]

#    id  v2 v1
# 1:  1 200 10
# 2:  3 200 20
# 3:  5 190 20
# 4:  6 290 15
Arun
  • 116,683
  • 26
  • 284
  • 387
1

You can use sqldf

library(sqldf)
sqldf('SELECT dat.*,dat1.v2
       FROM dat,dat1
       WHERE dat.id = dat1.id')
  id v1  v2
1  1 10 200
2  3 20 200
3  5 20 190
4  6 15 290

But using merge we get the same result

merge(dat,dat1)
  id v1  v2
1  1 10 200
2  3 20 200
3  5 20 190
4  6 15 290
agstudy
  • 119,832
  • 17
  • 199
  • 261
0

You can use an environment lookup via:

library(qdap)

A$v2 <- lookup(A$id, B)
A

> A
  id v1  v2
1  1 10 200
2  3 20 200
3  5 20 190
4  6 15 290

This is pretty fast on large data sets.

Dason
  • 60,663
  • 9
  • 131
  • 148
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
  • I have an error to install qdap, such as **Error : .onLoad failed in loadNamespace() for 'rJava', details: call: stop("No CurrentVersion entry in '", key, "'! Try re-installing Java and make sure R and Java have matching architectures.") error: object 'key' not found Error: package/namespace load failed for ‘qdap’** Do you have any suggestions? – POTENZA Feb 10 '13 at 02:10
  • Yes you have a different version of R and java. Check out this link: http://stackoverflow.com/questions/10545458/rjava-warning-meaning/10859487#10859487 where I explain this in more detail. – Tyler Rinker Feb 10 '13 at 03:10
  • This may also be useful: http://stackoverflow.com/questions/14631494/problems-loading-rjava-package-on-win7#comment20438086_14631494 When you get it can you state what you did for other users? – Tyler Rinker Feb 10 '13 at 04:06