首页 > 解决方案 > str_c 构建一个引号包裹的逗号分隔向量

问题描述

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

输出: "Sepal.Length","Sepal.Width","Petal.Length","Petal.Width" 它让我接近我想要的(我并不关心逗号后缺少的空格)但我之后无法删除反斜杠,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)

标签: rstringr

解决方案


您可以使用 :

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"

推荐阅读