Reputation: 21
I'm very new to R and I know this is a really simple question but I can't seem to figure it out.
I am given the character vector more.colors:
more.colors <- c("red", "yellow", "blue", "green", "magenta", "cyan")
And I have to use the more.colors vector, rep() and seq() to create the vector:
"red" "yellow" "blue" "yellow" "blue" "green"
"blue" "green" "magenta" "green" "magenta" "cyan"
So far all I have is c(more.colors[1:3], more.colors[2:3], more.colors[4], more.colors[3:4], more.colors[5], more.colors[4:5], more.colors[6])
which doesn't use rep() or seq().
Any help would be much appreciated!
Upvotes: 1
Views: 111
Reputation: 173793
If you look at the sequence of the target vector, it is equivalent to more.colors[c(1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6)]
, so this is really an exercise in using rep
and seq
to get the sequence c(1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6)
.
I think this exercise is getting you to use the two different methods of rep
; that is, you can repeat each element of the vector n
times if you do each = n
, and you can get the whole vector to repeat n
times if you pass times = n
So the solution here is to repeat the sequence "1 to 3" four times, and add it to the sequence "0 to 4" where each element is repeated three times
more.colors[rep(seq(0, 3), each = 3) + rep(seq(1, 3), times = 4)]
#> [1] "red" "yellow" "blue" "yellow" "blue" "green" "blue"
#> [8] "green" "magenta" "green" "magenta" "cyan"
Upvotes: 2
Reputation: 786
This would work:
new.colors <- c()
for (i in 1:(length(more.colors)-2)) {
new.colors <- c(new.colors, more.colors[i:(i+2)])
}
Upvotes: 1