How to access the last value in a vector?

后端 未结 11 1139
栀梦
栀梦 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.)

    0 讨论(0)
  • 2020-11-28 18:27

    I use the tail function:

    tail(vector, n=1)
    

    The nice thing with tail is that it works on dataframes too, unlike the x[length(x)] idiom.

    0 讨论(0)
  • 2020-11-28 18:32

    The dplyr package includes a function last():

    last(mtcars$mpg)
    # [1] 21.4
    
    0 讨论(0)
  • 2020-11-28 18:32

    I just benchmarked these two approaches on data frame with 663,552 rows using the following code:

    system.time(
      resultsByLevel$subject <- sapply(resultsByLevel$variable, function(x) {
        s <- strsplit(x, ".", fixed=TRUE)[[1]]
        s[length(s)]
      })
      )
    
     user  system elapsed 
      3.722   0.000   3.594 
    

    and

    system.time(
      resultsByLevel$subject <- sapply(resultsByLevel$variable, function(x) {
        s <- strsplit(x, ".", fixed=TRUE)[[1]]
        tail(s, n=1)
      })
      )
    
       user  system elapsed 
     28.174   0.000  27.662 
    

    So, assuming you're working with vectors, accessing the length position is significantly faster.

    0 讨论(0)
  • 2020-11-28 18:32

    Package data.table includes last function

    library(data.table)
    last(c(1:10))
    # [1] 10
    
    0 讨论(0)
提交回复
热议问题