Reputation: 333
I´m new to R and I´d like to execute the following simple code:
vec_color <- c("red", "blue", "green", "yellow", "orange")
col_vec_final = c()
i <- 1
while (i <= 3)
{
col_vec_final <- c(col_vec_final, i = vec_color[i])
i <- i+1
}
I´d expect to get the following output:
col_vec_final
1 2 3
"red" "blue" "green"
However I only get the following:
col_vec_final
i i i
"red" "blue" "green"
Could you please help me with that and tell me whats wrong with my code?
Thank´s in advance!
Upvotes: 1
Views: 2712
Reputation: 99391
vec_color <- c("red", "blue", "green", "yellow", "orange")
Firstly, keep in mind that you can vectorize this entire operation and do it all in one line, like this -
l <- seq_len(3)
( col_vec_final <- setNames(vec_color[l], l) )
# 1 2 3
# "red" "blue" "green"
As far as your while()
loop goes, I'd recommend you allocate the result vector first, as it's better practice and a lot more efficient than building a vector in a loop -
n <- 3
col_vec_final <- vector(class(vec_color), n)
then do the following -
i <- 1
while (i <= n)
{
col_vec_final[i] <- vec_color[i]
names(col_vec_final)[i] <- i
i <- i + 1
}
col_vec_final
# 1 2 3
# "red" "blue" "green"
Upvotes: 1