Wednesday, 13 December 2017

How to join data tables in R (inner,outer,left,right)?

This is a replication of a previous post ( href="https://stackoverflow.com/questions/1299871/how-to-join-data-frames-in-r-inner-outer-left-right">How
to join (merge) data frames (inner, outer, left, right)?), using
data.table() rather than data.frame().



Suppose I have two data tables:



library(data.table)
dt1
= data.table(CustomerID=c(1:6),Product=c(rep("Toaster",3),rep("Radio",3)))
dt2
= data.table(CustomerID=c(2,4,6),State=c(rep("Alabama",2),rep("Ohio",1)))


dt1

CustomerID Product
1: 1
Toaster
2: 2 Toaster
3: 3 Toaster
4: 4 Radio
5:
5 Radio
6: 6 Radio
dt2
CustomerID State
1: 2
Alabama

2: 4 Alabama
3: 6
Ohio

setkey(dt1,CustomerID)
setkey(dt2, CustomerID)



The default using
merge() on a data.table is a right
join. What's the syntax for the others?



#Outer
join:


#Right outer (data.table default):
dtro
<- merge(dt1,dt2); dtro

CustomerID Product State
1:
2 Toaster Alabama
2: 4 Radio Alabama
3: 6 Radio
Ohio

#Left outer:


#Cross join:

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...