這是我的資料框:
col1 <- c("hello my name is", "Nice to meet you", "how are you")
col2 <- c("dog", "Cats", "Frogs are cool")
col3 <- c("Pause", "breathe in and out", "what are you talking about")
df <- data.frame(col1, col2, col3)
我想gsub在我的 df 中應用以下變數:
vars <- c("col1", "col2")
我想用gsub大寫每個單元格的第一個字母:
df <- df %>%
as_tibble() %>%
mutate(across(vars), gsub, pattern = "^(\\w)(\\w )", replacement = "\\U\\1\\L\\2", perl = TRUE)
但我收到以下錯誤:
Error in `mutate_cols()`:
! Problem with `mutate()` input `..2`.
? `..2 = gsub`.
x `..2` must be a vector, not a function.
Run `rlang::last_error()` to see where the error occurred.
任何指導將不勝感激!
uj5u.com熱心網友回復:
修復你的括號:
df %>%
as_tibble() %>%
mutate(across(any_of(vars), gsub, pattern = "^(\\w)(\\w )", replacement = "\\U\\1\\L\\2"))
雖然我不認為你的正則運算式在做你想做的事:
# A tibble: 3 x 3
col1 col2 col3
<chr> <chr> <chr>
1 UhLello my name is UdLog Pause
2 UNLice to meet you UCLats breathe in and out
3 UhLow are you UFLrogs are cool what are you talking about
uj5u.com熱心網友回復:
另一個簡單的解決方案是更改為句子大小寫:
library(tidyverse)
df |>
as_tibble() |>
mutate(across(all_of(vars), str_to_sentence))
#> # A tibble: 3 x 3
#> col1 col2 col3
#> <chr> <chr> <chr>
#> 1 Hello my name is Dog Pause
#> 2 Nice to meet you Cats breathe in and out
#> 3 How are you Frogs are cool what are you talking about
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/536382.html
標籤:rgsub变异
