str_c to build a quotation-wrapped comma separated vector

I asked this on stackoverflow and I got an alternative solution, but I'm interested in understanding why str_c and str_remove_all aren't behaving the way I thought they would/giving a regex error.

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

Output: "Sepal.Length","Sepal.Width","Petal.Length","Petal.Width" It gets me close to what I want (I don't really care about the space missing after the comma) but I can't remove the backslash afterwards with str_remove_all because it doesn't recognize the escaped backslash

Ideal: "Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"
Attempt:
iris %>% select(where(is.numeric)) %>% colnames() %>% str_c(., collapse = '",') str_remove_all(., "\\")

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

This gives you a quotation-wrapped, comma-separated vector. As mentioned on SO, the slashes you see in your R console are not in the vector itself, they only show in your console as escape characters for the quotation marks.

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

If you add cat() at the end of the pipe you will not see the slashes

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

Use my first pipe above and write the results to a text file

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

When you open that text file, there are no slashes.

This topic was automatically closed 21 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.