简体   繁体   中英

Using the rep() function in R

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 xyyx 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?

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, eg:

> 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, eg:

> 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM