How to access the last value in a vector?

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

提交回复
热议问题