首页 > 解决方案 > 将用户定义的函数应用于小标题

问题描述

我创建了一个用户定义的函数,它将在文本中搜索某些值,然后返回一个不同的值。这对每个单独的调用都很好,但是,当我尝试在 Tidyverse 中使用它时,使用 mutate 它不再起作用。我收到警告:

警告信息:

在 if (grepl("Unique", textValue)) { : 条件长度 > 1 并且只使用第一个元素

我猜它与类型和格式有关,但不知道如何解决它。

# create fake data
P1 = c("Unique Claims", "Unique Records", "Spend Today", "Spend Yesterday", "% Returned", "% Claimed")
P2 = as.tibble(P1) 


#create function
assignFormat <- function (textValue = as.character()) {
  if (grepl("Unique", textValue) > 0) {
    numFormat = "Comma"
  } else if (grepl("Spend", textValue) > 0) {
    numFormat = "Currency"
  } else if (grepl("%", textValue, ) > 0 ) {numFormat = "Percent"}
    else numFormat = "Other"

  return(numFormat)
}


#test function - works fine
assignFormat("% of CLaims")
assignFormat("Unique Records")
assignFormat("Total Spend")

#doesn't work
P3 = P2 %>%
     mutate(y = assignFormat(value))

我尝试过的事情:直接在 mutate 中使用 GREP 切换到 grep - 创建三个向量

选项和帮助表示赞赏!

标签: rfunctiondplyr

解决方案


dplyr如果您使用rowwise分组,许多字符串函数会按预期工作

#does work
P3 = P2 %>%
  rowwise() %>% 
  mutate(y = assignFormat(value)) %>% 
  ungroup()

推荐阅读