以下是我所拥有的:
# create fake data in representative format
data <- data.frame(test = c('a2','t33b','s5c','d102','e4e','df1f'))
data <- as_tibble(data)
当前代码:
data2 <- data %>% summarise(test2 = toString(test)) %>% ungroup()
输出:
# A tibble: 1 x 1
test2
<chr>
1 a2, t33b, s5c, d102, e4e, df1f
但是,我如何才能让字符串中每个"单词"中的项目都像这样用单引号括起来呢?:
期望输出:
test2
<chr>
1 'a2', 't33b', 's5c', 'd102', 'e4e', 'df1f'
原因是我想稍后使用paste0为SQL查询创建一个带引号的字符串列表。非常感谢。
类似问题:
在R中,用单引号和逗号分隔的打印矢量
在每个组中将一列折叠/连接/聚合为一个逗号分隔的字符串
我们可以用sub
插入单引号。
library(tidyverse)
data <- tibble(test = c('a2','t33b','s5c','d102','e4e','df1f'))
data |>
summarise(test = paste(sub("(^.*$)", "'\1'", test), collapse = ", "))
#> # A tibble: 1 x 1
#> test
#> <chr>
#> 1 'a2', 't33b', 's5c', 'd102', 'e4e', 'df1f'