Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions R/pkg/NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ exportMethods("abs",
"hex",
"hour",
"hypot",
"ifelse",
"initcap",
"isNaN",
"isNotNull",
Expand Down
19 changes: 19 additions & 0 deletions R/pkg/R/functions.R
Original file line number Diff line number Diff line change
Expand Up @@ -179,3 +179,22 @@ setMethod("when", signature(condition = "Column", value = "ANY"),
jc <- callJStatic("org.apache.spark.sql.functions", "when", condition, value)
column(jc)
})

#' ifelse
#'
#' Evaluates a list of conditions and returns `yes` if the conditions are satisfied.
#' Otherwise `no` is returned for unmatched conditions.
#'
#' @rdname column
setMethod("ifelse",
signature(test = "Column", yes = "ANY", no = "ANY"),
function(test, yes, no) {
test <- test@jc
yes <- ifelse(class(yes) == "Column", yes@jc, yes)
no <- ifelse(class(no) == "Column", no@jc, no)
jc <- callJMethod(callJStatic("org.apache.spark.sql.functions",
"when",
test, yes),
"otherwise", no)
column(jc)
})
3 changes: 2 additions & 1 deletion R/pkg/inst/tests/test_sparkSQL.R
Original file line number Diff line number Diff line change
Expand Up @@ -727,11 +727,12 @@ test_that("greatest() and least() on a DataFrame", {
expect_equal(collect(select(df, least(df$a, df$b)))[, 1], c(1, 3))
})

test_that("when() and otherwise() on a DataFrame", {
test_that("when(), otherwise() and ifelse() on a DataFrame", {
l <- list(list(a = 1, b = 2), list(a = 3, b = 4))
df <- createDataFrame(sqlContext, l)
expect_equal(collect(select(df, when(df$a > 1 & df$b > 2, 1)))[, 1], c(NA, 1))
expect_equal(collect(select(df, otherwise(when(df$a > 1, 1), 0)))[, 1], c(0, 1))
expect_equal(collect(select(df, ifelse(df$a > 1 & df$b > 2, 0, 1)))[, 1], c(1, 0))
})

test_that("group by", {
Expand Down