Selecting elements within the vector inaccuracy in Swirl?

226 Views Asked by At

I made an anonymous function to select the first element of the vector Then to select the last element of the vector. When I selected the last element, it said Incorrect. When I selected the second element, it said correct. I am tracking R is 1 based. NOT zero based. So when I select the last element of the vector should it not be x[3]???

The first part: My function, what I used to select the first element per the problem. | Try using evaluate() along with an anonymous function to return the first element of | the vector c(8, 4, 0). Your anonymous function should only take one argument which | should be a variable x.

evaluate(function(x){x[1]}, c(8, 4, 0)) [1] 8

| You got it!

The second part of the problem: Select the last element of the vector

| Now try using evaluate() along with an anonymous function to return the last element | of the vector c(8, 4, 0). Your anonymous function should only take one argument which | should be a variable x.

evaluate(function(x){x[3]}, c(8, 4, 0)) [1] 0

| That's not exactly what I'm looking for. Try again. Or, type info() for more options.

| You may need to recall how to index vector elements. Remember that your anonymous | function should only have one argument, and that argument should be named x. Using | the length() function in your anonymous function may help you.

evaluate(function(x){x[2]}, c(8, 4, 0)) [1] 4

| You are really on a roll!

What the heck, I had to use x[2] in order to select the last element of the vector. Why is it not x[3]?

I am using Swirl right now in R.

1

There are 1 best solutions below

5
Len Greski On

What Swirl expected was to use the length() argument to find the last element in the vector, as in:

evaluate(function(x){x[length(x)]}, c(8, 4, 0))

This exercise is in module 9 of the R programming swirl course. About 2/3 through the lesson, I replicate the correct answer.

enter image description here