简体   繁体   中英

add a column from a dataset to another dataset in R

Suppose i have two dataset

ds1

NO   ID      DOB         ID2   count
1   4083    2007-10-01  3625    5
2   4408    2008-07-01  3603    2
3   4514    2007-07-01  3077    3
4   4396    2008-05-01  3413    5
5   4222    2003-12-01  3341    1

ds2

loc  share
12    445
23    4
10    56
1     1
23    34

I want "share" column of ds2 to be added to ds1 so that it would look like

dsmerged

NO    ID      DOB         ID2   count   share
1   4083    2007-10-01  3625    5      445
2   4408    2008-07-01  3603    2      4
3   4514    2007-07-01  3077    3      56
4   4396    2008-05-01  3413    5      1
5   4222    2003-12-01  3341    1      34

i tried merge as dsmerged <- merge(ds1[,c(1:5)],ds2[,c(2)])

But what it does is it duplicates the dataset (5*5=25 rows) while it does add "share" column. i dont want that duplicate values obviously. Thank you

If you know that the rows represent the same id then you can just cbind

ds3 <- cbind(ds1, share = ds2$share) 

but it would be better if you had an id to join on.

Using dplyr

library(dplyr)
bind_cols(ds1, ds2['share'])

Or with data.table

setDT(ds1)[, share := ds2[["share"]]]

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