1
votes

I have a Vector and want to remove elements from the Vector. How can I do it in Scala?My input is a Vector[2.0, 3.0, 0.3, 1.0, 4.0] -->Vector[Double] and I want a Vector[2.0, 0.3, 4.0] as output, so I want to remove the element with the index 1 and 3 from my input Vector...

def removeElementFromVector(input: Vector) = {   
  val inputAsArray = input.toArray

  inputAsArray

  // ...
  val reducedInputAsVector = inputAsArray.toVector 
}
5
Just to be clear, when you say that you want to remove an element how does that concretely happen ? Can you give an example input and output about what you are looking for ? - eliasah

5 Answers

1
votes

Yes, you can use filter to achieve it, but we need to add index to remove element at an index:

Ex: Your vector (scala.collection.immutable.Vector[Double]):

scala> val v1 = val v1 = Vector(2.2, 3.3, 4.4, 5.5, 6.6, 4.4)

Output: Vector(2.2, 3.3, 4.4, 5.5, 6.6, 4.4)

Now, we will remove element at index 2:

scala> var indexRemove=2

scala> val v2 = v1.zipWithIndex.filter(x => x._2!=indexRemove).map(x=>x._1).toVector
Output: Vector(2.2, 3.3, 5.5, 6.6, 4.4)

Now, we will remove element at index 3

scala> var indexRemove=3
scala> val v2 = v1.zipWithIndex.filter(x => x._2!=indexRemove).map(x=>x._1).toVector
Output: Vector(2.2, 3.3, 4.4, 6.6, 4.4)

Hope this helps.

0
votes

My input is: Vector[2.0, 3.0, 0.3, 1.0, 4.0] -->Vector[Double] and I want a Vector[2.0, 3.0, 0.3, 4.0] as output, so I want to remove the element with the index 1 and 3 from my input Vector. Sry for my question was not clear enough..

0
votes

You can use filter method to remove them.

> val reducedInputVector = input.filter(x => !(Array(1,3) contains input.indexOf(x)))
reducedInputVector: scala.collection.immutable.Vector[Double] = Vector(2.0, 0.3, 4.0)
0
votes

I solved it with apply:

val vec1 = Vector(2.0,3.0,0.3,1.0, 4.0)
val vec2 = Vectors.dense(vec1.apply(0), vec1.apply(1),vec1.apply(2), vec1.apply(4))

the output is

vec1: scala.collection.immutable.Vector[Double] = Vector(2.0, 3.0, 0.3, 1.0, 4.0)
vec2: org.apache.spark.mllib.linalg.Vector = [2.0,3.0,0.3,4.0]
0
votes
def deleteItem[A](row: Vector[A], item: Int): Vector[A] = {
  val (a,b) = row.splitAt(item)
  if (b!=Nil) a ++ b.tail else a
}