How to access the last value in a vector?

后端 未结 11 1287
栀梦
栀梦 2020-11-28 18:05

Suppose I have a vector that is nested in a dataframe one or two levels. Is there a quick and dirty way to access the last value, without using the length() fu

11条回答
  •  一个人的身影
    2020-11-28 18:25

    Combining lindelof's and Gregg Lind's ideas:

    last <- function(x) { tail(x, n = 1) }
    

    Working at the prompt, I usually omit the n=, i.e. tail(x, 1).

    Unlike last from the pastecs package, head and tail (from utils) work not only on vectors but also on data frames etc., and also can return data "without first/last n elements", e.g.

    but.last <- function(x) { head(x, n = -1) }
    

    (Note that you have to use head for this, instead of tail.)

提交回复
热议问题