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 view kwarg to first and last #2951

Merged
merged 7 commits into from
Dec 1, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
18 changes: 14 additions & 4 deletions src/abstractdataframe/abstractdataframe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -486,11 +486,16 @@ Get the first row of `df` as a `DataFrameRow`.
Base.first(df::AbstractDataFrame) = df[1, :]

"""
first(df::AbstractDataFrame, n::Integer)
first(df::AbstractDataFrame, n::Integer, view::Bool=false)

Get a data frame with the `n` first rows of `df`.

If `view=false` a freshly allocated `DataFrame` is returned.
If `view=true` then a `SubDataFrame` view into `df` is returned.
"""
Base.first(df::AbstractDataFrame, n::Integer) = df[1:min(n, nrow(df)), :]
function Base.first(df::AbstractDataFrame, n::Integer, view::Bool=false)
return view ? Base.view(df, 1:min(n ,nrow(df)), :) : df[1:min(n, nrow(df)), :]
end

"""
last(df::AbstractDataFrame)
Expand All @@ -500,11 +505,16 @@ Get the last row of `df` as a `DataFrameRow`.
Base.last(df::AbstractDataFrame) = df[nrow(df), :]

"""
last(df::AbstractDataFrame, n::Integer)
last(df::AbstractDataFrame, n::Integer, view::Bool=false)

Get a data frame with the `n` last rows of `df`.

If `view=false` a freshly allocated `DataFrame` is returned.
If `view=true` then a `SubDataFrame` view into `df` is returned.
"""
Base.last(df::AbstractDataFrame, n::Integer) = df[max(1, nrow(df)-n+1):nrow(df), :]
function Base.last(df::AbstractDataFrame, n::Integer, view::Bool=false)
return view ? Base.view(df, max(1, nrow(df)-n+1):nrow(df), :) : df[max(1, nrow(df)-n+1):nrow(df), :]
end


"""
Expand Down
5 changes: 5 additions & 0 deletions test/dataframe.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1105,6 +1105,11 @@ end
@test last(df, 6) == DataFrame(A=5:10)
@test last(df, 1) == DataFrame(A=10)

@test first(df, 6, true) isa SubDataFrame
@test first(df, 6, false) isa DataFrame
@test last(df, 6, true) isa SubDataFrame
@test last(df, 6, false) isa DataFrame

@test_throws ArgumentError only(df)
@test_throws ArgumentError only(DataFrame())
df = DataFrame(a=1, b=2)
Expand Down