Condition on rows content of dataframe in Spark scala

Viewed 8547

I have the following dataframe:

+--------+---------+------+
|  value1| value2  |value3|
+--------+---------+------+
|   a    |  2      |   3  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   b    |  5      |   4  |
+--------+---------+------+
|   c    |  3      |   4  |
+--------+---------+------+

I would like to put the result of value2/value3 of the rows when value1=b, then add it for all the rows (even the rows that do not belong to b) in a new field with name of "result". It means that another column must be added to the dataframe. For example for all the rows, the result of 5/4 (I choose it since, it is for b) should be added to dataframe. I know that, I should use this code:

 val dataframe_new = Dataframe.withColumn("result", $"value1" / $"value2")
 Dataframe.show()

However how can I put the condition in such a way that, it added it to all rows. The output should be like below:

+---+---+---+------+
| v1| v2| v3|result|
+---+---+---+------+
|  a|  2|  3|  1.25|
|  b|  5|  4|  1.25|
|  b|  5|  4|  1.25|
|  c|  3|  4|  1.25|
+---+---+---+------+

Can you help me? Thanks in advance.

2 Answers
Related