0

I am taking Microsoft's online Data Science programme. In one of the courses, I ran into an error with some code which I feel is logical and should work just fine. I'm using DataCamp's IDE.

Here is the question that I was asked (the variables were pre-created and I was to use them in my code. Unfortunately, I can't provide the data stored in the variables):-

Create a new list named key_skills, that contains three elements (in this order): - The second element of the topics vector inside the skills list. - The second element of the context factor inside the skills list. - The last element of the logical vector inside the list_info list, that's inside skills.

This is my code for the question :-

key_skills <- list(
    skills$topics[2], 
    skills$context[2], 
    skills$list_info[length(skills$list_info)]
)

Why is the code incorrect? The code for the last element in the list key_skills was marked wrong. I believe it should work just fine.

EDIT : I looked up the variable in the IDE, the logical vector is the 2nd one inside skills$list_info, the correct code for the last part is skills$list_info[[2]][length(skills$list_info[[2]])]

Thank you everyone!

another solution : key_skills<- list(skills[[1]][2],skills[[2]][2],skills[[4]][[2]][4])

Rudhraksh
  • 27
  • 5
  • "Unfortunately, I can't provide the data stored in the variables" -- we don't need your data, nor do we need your background info or the actual problem you worked on. Read https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/28481250#28481250 – Frank Sep 09 '17 at 05:49

3 Answers3

5

Since list_info is a list, it should be:

key_skills <- list(skills$topics[2], skills$context[2], 
skills$list_info[[length(skills$list_info)]])

list[index] gives you a list, while list[[index]] gives you the object at the index, which in your case should be the last element of the boolean vector in skills$list_info.

tushaR
  • 3,083
  • 1
  • 20
  • 33
0

It should work fine, yes. There is however a simpler way to get the last element, using tail:

tail(skills$list_info, 1)
Dominic Comtois
  • 10,230
  • 1
  • 39
  • 61
0

Without an example dataset it's difficult to know for sure, but given your description of the problem it seems that since skills$list_info is a list, it may have several vectors in it. One of them is of class logical. So first determine which one is logical, then get the last element of that vector. Something like this:

inx <- which(sapply(skills$list_info, is.logical))
skills$list_info[[inx]][length(skills$list_info[[inx]])]

But, like I've said, without data it's impossible to be sure if this code does the job.

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66