sparkr:如何合并多个“when”/“otherwise”多个条件

wf82jlnq  于 2021-07-14  发布在  Spark
关注(0)|答案(1)|浏览(310)

我试图在basea multiple conditions中创建一个新列,但是我发现我不能使用只有一个的multiple when子句,我被限制使用如下内容:

test1 <- test %>%  withColumn("newCol1", otherwise(when(column("oldCol1") == 1, lit("one")), 
                                                    otherwise(when(column("oldCol1") == 2,lit("two")),
                                                              lit("other")))) %>%
  select(column("oldCol1"), column("newCol1"))

这给了我预期的结果:

oldCol1 newCol1
1          1     one
2          1     one
3          2     two
4          4   other
5          4   other
6          1     one

sparkr中的when函数有更清晰的用法吗?

7gs2gvoe

7gs2gvoe1#

你可以试试 coalesce -使 when 声明:

test1 <- test %>% withColumn(
    "newCol1", 
    coalesce(
        when(column("oldCol1") == 1, lit("one")),
        when(column("oldCol1") == 2, lit("two")),
        lit("other")
    )
) %>% select(column("oldCol1"), column("newCol1"))

相关问题