error while checking double space in name column

i am updating the new column which will show if the name column have double space or extra space but its showing error.

i havemore than one column in my database

df7 <- data.frame(name_1 = c("ttt, hbue","mna,ssu huna","vga,  pahk","hja, dhyn","cct, indo","nhu,nhuv"))

countSpaces <- function(s) { sapply(gregexpr(" ", s), function(p) { sum(p>=0) } ) }
name <-  "name_1"

df7 <- df7 %>% mutate(across(`1. double space in name` = ifelse(countSpaces(df7[[name]])>1,"1. name contains uneccessary space"," ")))

The error is there because you are using across incorrectly. However, the whole thing can be encoded in a simpler fashion:

library(dplyr)
library(stringr)

df7 |>
  mutate(
    double_space = str_count(name_1, "\\s\\s") > 0,
    message = if_else(double_space, "Name contains unnecessary double space", "")
)
countSpaces <- function(x) lengths(regmatches(x, gregexpr(" ", x)), use.names = FALSE)
df7 <- data.frame(name_1 = c("ttt, hbue","mna,ssu huna","vga,  pahk","hja, dhyn","cct, indo","nhu,nhuv"))
df7$spaces <- sapply(df7$name_1, countSpaces)
df7
#>         name_1 spaces
#> 1    ttt, hbue      1
#> 2 mna,ssu huna      1
#> 3   vga,  pahk      2
#> 4    hja, dhyn      1
#> 5    cct, indo      1
#> 6     nhu,nhuv      0

Created on 2023-05-18 with reprex v2.0.2

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.