2
votes

I have a DataFrame X. In sparkR I can find the first row by typing

first(X)

Now I want to find the last one. 'last' is a aggregate function.

But when I type last(X) in sparkR I get this message Error in (function (classes, fdef, mtable) : unable to find an inherited method for function ‘last’ for signature ‘"DataFrame"’ How can that be and how can I solve this?

In addition I can do head(X) to get the first rows but how can I get the last rows in X ?

1

1 Answers

3
votes

If your DataFrame is sortable, or if you have added row.numbers, sort it descending en take first:

dfDesc <- arrange(df, desc(abs(df$rowNumber)))
first(dfDesc)

If you do not want to sort, you can add a constant row and use last-function of groupBy:

df <- data.frame(a=c(1,2),b=c(2,3))
DF <- createDataFrame(sqlContext,df)

DF <- withColumn(DF, "constant", DF$a * 0)

lastLine    <- agg(groupBy(DF, DF$constant), a = last(DF[["a"]]), b = last(DF[["b"]]))
collect(lastLine)