11

I want to get the every last element in a list. I have found that by using sapply function, the first element can be obtained.

sapply(a,`[`,1)

However, I don't actually understantd what is the meaning of [, and how to get the last element in a similar way. This code doesn't work.

sapply(a,`]`,1)
Roy
  • 539
  • 1
  • 4
  • 12
  • 14
    `sapply(a, tail, 1)` – akrun Jun 22 '18 at 07:11
  • 2
    The `[` is a reference to the indexing operation. It's just what gets called when you do `a[1]` – Rohit Jun 22 '18 at 07:13
  • 6
    ``mapply(`[`, a, lengths(a))`` – Roland Jun 22 '18 at 07:15
  • 1
    When you call `a[1]` the parser interprets it as `'['(a,1)`, you could see the former as a mere shortcut.The function `]` doesn't exist. You can use the function `[` directly, in practice I believe it is useful only when passing it as an argument like you did in your example – moodymudskipper Jun 22 '18 at 07:21

3 Answers3

15

I came here with the same question, and saw that the answer must have been overlooked, but for me @akrun as usual had the answer that worked for me. So in the absence of a correct answer it is:

sapply(a, tail, 1)

mattbawn
  • 1,358
  • 2
  • 13
  • 33
6

By using the length of a list/vector:

a[length(a)]

For the last "n"th element:

a[length(a)-n+1]

Example:

a[length(a)-1] #the 2nd last element
a[length(a)-2] #the 3rd last element
a[length(a)-8] #the 9th last element
uguros
  • 356
  • 2
  • 6
  • 19
-3

If I get your query correctly, it could simply be :

tail(a, n = 1)
mdag02
  • 1,035
  • 9
  • 16
Akshay
  • 76
  • 4