Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add crossjoin #531

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/DataFrames.jl
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ export @~,
combine,
complete_cases,
complete_cases!,
crossjoin,
cut,
DataFrame,
DataFrameRow,
Expand Down
33 changes: 33 additions & 0 deletions src/dataframe/join.jl
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,36 @@ function Base.join(df1::AbstractDataFrame,
throw(ArgumentError("Unknown kind of join requested"))
end
end

##
## Crossjoin
##

let
global crossjoin
function crossjoin(xs::Union(DataFrame, (Symbol, AbstractVector))...)
lens = Int[xlen(x) for x in xs]
d = DataFrame()
times = 1
each = prod(lens)
for i in 1:length(xs)
ilen = lens[i]
each = fld(each, ilen)
addx!(d, xs[i], times, each)
times *= ilen
end
d
end

xlen(x::DataFrame) = size(x, 1)
xlen(x::(Symbol, AbstractVector)) = size(x[2], 1)

function addx!(d::DataFrame, x::DataFrame, times::Int, each::Int)
for c in x
addx!(d, c, times, each)
end
end
function addx!(d::DataFrame, x::(Symbol, AbstractVector), times::Int, each::Int)
d[x[1]] = rep(x[2], times, each)
end
end
16 changes: 15 additions & 1 deletion test/join.jl
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,18 @@ module TestJoin
@test_throws join(df1, df2)

join(df1, df2, on = [:A, :B])
end


df = DataFrame(A = 1:2, B = ['b', 'a'])
t1 = (:C, [2.4, 3.6])
t2 = (:D, [2, 3])

crossjoin(df, df, t1, t2, df, t2)

dft = DataFrame(A = [1, 1, 1, 1, 2, 2, 2, 2],
B = ['b', 'b', 'b', 'b', 'a', 'a', 'a', 'a'],
C = [2.4, 2.4, 3.6, 3.6, 2.4, 2.4, 3.6, 3.6],
D = [2, 3, 2, 3, 2, 3, 2, 3])

@test crossjoin(df, t1, t2) == dft
end