Use of concatenate with indexing

Hi all,
I just started out in the Data Analyst path, beginning with the intro to R courses. I’ve encountered a question around the use of concatenation.

In the practice problem below, you’re asked to create a new vector, “stem_grades,” that contains only the grades for math and chemistry, which are positions 1 and 2, respectively, in the vector “final_scores.” I thought that when creating a new vector it was always necessary to use concatenate. So: “stem_grades <-- c (math, chemistry),” which would be “stem_grades <-- c (final_scores [1:2]).” This produces the correct answer.

However, the expression "stem_grades <-- (final_scores [1:2]) ALSO produces the right answer. Does this mean that putting the concatenate in front of the parentheses is redundant in R? If so, why is this?

Attached are two screenshots showing what I’m talking about.

Thanks for any guidance!

-Ben


You use concatenate/combine function to combine multiple elements together, so when you want to combine 2 element says 88 and 86 together to create a vector of [88 , 86] you use the combine function.

However, since you already have a combined vector, final_scores, you directly slice from the vector and assign it to stem_grades, basically you are telling R to grab the first to second element from the vector final_scores, and store it in stem_grades, you don’t need to use the combine function for that since you are slicing directly from a vector, not combining elements to create new one – hence the correct answer.

And no, using the combine function is not redundant, you still need it if you want to combine elements. Just in the scenario where you are slicing or trying to subset your data, you don’t need to use the combine function in conjunction with [ ’ ’ ], not in the context of what you are trying to do at least.

3 Likes

Thanks, DerpMaiden–very helpful!