Newman
Newman

Reputation: 1

Concatenating elements within a single vector using for loop

I have a vector with 861 elements called 'source_vector' in R. For each element, I would like for it to concatenate with itself and every other value in the vector that comes after it. Each result would be stored in another vector called 'result_vector'. I tried using for loops.

result_vector <- c()
> for (i in source_vector){
+     for (l in source_vector[which(source_vector == i):length(source_vector)]){
+         result_vector <- c(result_vector, paste(i, l))
+     }
+ }

It is taking a long time to run this. Are there any other solutions that can cut down the running time?

Upvotes: 0

Views: 94

Answers (1)

Ben
Ben

Reputation: 30474

You could try using lapply across each element of your vector. Let me know if this gives the same result (and is faster).

result_vector <- unlist(lapply(
  1:length(source_vector), 
  function(x) {
    paste(source_vector[x], source_vector[x:length(source_vector)])
  }
))

Upvotes: 0

Related Questions