str_c 构建引号包裹的逗号分隔向量

str_c to build a quotation-wrapped comma separated vector

iris %>% select(where(is.numeric)) %>% colnames() %>% str_c(., collapse = '","')

输出:“Sepal.Length”、“Sepal.Width”、“Petal.Length”、“Petal.Width” 它让我接近我想要的东西(我真的不关心逗号后缺少的 space )但是我不能用 str_remove_all 删除反斜杠,因为它不识别转义反斜杠

理想:“Sepal.Length”、“Sepal.Width”、“Petal.Length”、“Petal.Width”

iris %>% select(where(is.numeric)) %>% colnames() %>% str_c(., collapse = '",') str_remove_all(., "\")

输出:Error in stri_replace_all_regex(string, pattern, fix_replacement(replacement), : Unrecognized backslash escape sequence in pattern. (U_REGEX_BAD_ESCAPE_SEQUENCE)

您可以使用:

library(dplyr)

iris %>% 
      select(where(is.numeric)) %>% 
      colnames() %>% 
      sprintf('"%s"', .) %>%
      toString()

#[1] "\"Sepal.Length\", \"Sepal.Width\", \"Petal.Length\", \"Petal.Width\""

反斜杠不是实际字符串的一部分,这就是 R 显示双引号的方式。要查看实际字符串,您可以使用 cat :

iris %>% 
      select(where(is.numeric)) %>% 
      colnames() %>% 
      sprintf('"%s"', .) %>%
      toString() %>% 
      cat

#"Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"