Skip to content

Why value in mutate ifelse custom condition is treated as a vector #7107

@maciekbanas

Description

@maciekbanas

I can not understand why the value in the example below is treated as a vector and not scalar, when I try to put a simple string condition:

example_data <- data.frame(
  col_1 = c("John Test", "bobtest", "John Test"),
  col_2 = c(NA, "Bob Test", NA)
)

has_many_words <- function(char) {
  length(stringr::str_split_1(char, " ")) > 1
}

dplyr::mutate(
  example_data,
  col_2 = ifelse(is.na(col_2) & has_many_words(col_1), col_1, col_2)
)

Results in error:
Image

My question is if only way to approach mutate with customized condition is with map iterator? This works, though does not look nice:

dplyr::mutate(
  example_data,
  col_2 = purrr::map2(col_1, col_2, function(x, y) {
    ifelse(is.na(y) & has_many_words(x), x, y)
  })
)

Is there any other way, am I getting something wrong?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions