% str_split(", ") %>%-6ren">
gpt4 book ai didi

r - 如何为括号内并以逗号分隔的字符添加引号?

转载 作者:行者123 更新时间:2023-12-02 16:03:21 25 4
gpt4 key购买 nike

这个想法是为字符串列表表示中的所有字符串添加引号。

尝试了下一个:

input_text <- "[innovation manager, manager director, senior manager]"

scan(text=input_text, what="")

返回结果:

'[innovation" "manager,"    "manager"     "director,"   "senior"      "manager]'

预期输出可能如下所示:

'["innovation manager", "manager director", "senior manager"]'

我错过了什么?

最佳答案

可能的解决方案;

library(tidyverse)

input_text <- "[innovation manager, manager director, senior manager]"

input_text %>%
str_remove_all("\\[|\\]") %>%
str_split(", ") %>% unlist

#> [1] "innovation manager" "manager director" "senior manager"

但是,如果 OP 希望结果为单个字符串,则可以使用以下内容:

input_text %>% 
str_remove_all("\\[|\\]") %>%
str_split(", ") %>%
map(~ str_c('"',.x, '"')) %>% unlist %>%
str_flatten(collapse = ", ") %>%
str_c("[",.,"]")

#> [1] "[\"innovation manager\", \"manager director\", \"senior manager\"]"

关于r - 如何为括号内并以逗号分隔的字符添加引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70103699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com