Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
maciekbanas opened this issue Dec 4, 2024 · 2 comments
Closed

Comments

@maciekbanas
Copy link

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?

@joranE
Copy link
Contributor

joranE commented Dec 4, 2024

Both ifelse & dplyr::if_else expect a vector, not a scalar, condition; i.e. mutate doesn't do any "looping" for you over values in the column. So the expected use of ifelse or dplyr::if_else is that your condition is already vectorized, and hence the looping happens via that vectorization.

In this case I believe you just need to switch to str_split and use lengths() rather than length:

has_many_words <- function(char) {
  lengths(stringr::str_split(char, " ")) > 1
}

@DavisVaughan
Copy link
Member

I think @joranE is right that the main issue is that your has_many_words() function isn't vectorized quite right

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants