Using the rep() function in R

Viewed 25945

I am using the rep() functon in R with a vector:

c("x","y")[rep(c(1,2,2,1), times=4)]

Its output is:

"x" "y" "y" "x" "x" "y" "y" "x" "x" "y" "y" "x" "x" "y" "y" "x"

I don't understand why it is repeating x y y x here. If I use rep(c(1,2,2,1), times=4), it will repeat 1 2 2 1 four times.

Why is it using x and y here?

2 Answers

Your rep() code produces the vector:

> rep(c(1,2,2,1),times=4) [1] 1 2 2 1 1 2 2 1 1 2 2 1 1 2 2 1

You can reference the elements in the vector c("x","y") by using their index, e.g:

> c("x","y")[1] [1] "x"

provides the element at position 1 in your vector, which in this case is "x".

You can also reference this element multiple times by using a vector of indices, e.g:

> c("x","y")[c(1,1,1,1,1)] [1] "x" "x" "x" "x" "x"

returns the element at position one in your vector 5 times.

So when you supply R with c("x","y")[rep(c(1,2,2,1), times=4)], which is the same as c("x","y")[c(1,2,2,1,1,2,2,1,1,2,2,1,1,2,2,1)], what you return is the same pattern, but are replacing those values with the elements in the vector at those indices.

So instead of returning 1,2,2,1 repeated 4 times, you are returning the 1st,2nd, 2nd, and 1st elements of your vector repeated 4 times.

rep(x, ...)

Do you need to bring what you want to repeat inside the rep bracket.

What output are you looking for specifically?

rep(c("x", "y", "y", "x") , times = 4)

gives you

"x" "y" "y" "x" "x" "y" "y" "x" "x" "y" "y" "x" "x" "y" "y" "x"
Related