R:自动在文本前后添加引号

标签 r url data-manipulation quotes double-quotes

我正在使用 R 编程语言。我有一个名为“a”的数据框,其中有一列名为“V1”。 “a”中的每个条目都是一个 URL 链接,格式如下:

 1 https:blah-blah-blah.com/item/123/index.do
 2 https:blah-blah-blah.com/item/124/index.do
 3 https:blah-blah-blah.com/item/125/index.do

我试图在每个项目的前面和后面添加双引号(即“”),所以它们看起来像这样:

 1 "https:blah-blah-blah.com/item/123/index.do"
 2" https:blah-blah-blah.com/item/124/index.do"
 3 "https:blah-blah-blah.com/item/125/index.do"

使用之前的 stackoverflow 帖子 ( How to add quotes around each word in a string in R? ),我尝试了以下代码:

new_file = cat(gsub("\\b", '"',a$V1, perl=T))

new_file = cat(gsub("(\\w+)", '"\\1"', a$V1))

但是这些并没有产生预期的结果。有人可以告诉我我做错了什么吗?

谢谢

最佳答案

以我的拙见,paste0 应该可以完成这项工作。

  • 实际上 "' 执行相同的工作,但同时使用时表现不同。请参阅下面的两种情况 -

案例1

a <-  data.frame(V1 = c('https:blah-blah-blah.com/item/123/index.do',
                        'https:blah-blah-blah.com/item/124/index.do',
                        'https:blah-blah-blah.com/item/125/index.do'))

a
                                          V1
1 https:blah-blah-blah.com/item/123/index.do
2 https:blah-blah-blah.com/item/124/index.do
3 https:blah-blah-blah.com/item/125/index.do

a$V1 <- paste0('"', a$V1, '"')
a

                                            V1
1 "https:blah-blah-blah.com/item/123/index.do"
2 "https:blah-blah-blah.com/item/124/index.do"
3 "https:blah-blah-blah.com/item/125/index.do"

案例2

a <-  data.frame(V1 = c("https:blah-blah-blah.com/item/123/index.do",
                        "https:blah-blah-blah.com/item/124/index.do",
                        "https:blah-blah-blah.com/item/125/index.do"))
 
a
                                          V1
1 https:blah-blah-blah.com/item/123/index.do
2 https:blah-blah-blah.com/item/124/index.do
3 https:blah-blah-blah.com/item/125/index.do

a$V1 <- paste0("'", a$V1, "'")
a
                                            V1
1 'https:blah-blah-blah.com/item/123/index.do'
2 'https:blah-blah-blah.com/item/124/index.do'
3 'https:blah-blah-blah.com/item/125/index.do'

关于R:自动在文本前后添加引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67041074/

相关文章:

r - R中的目标变量重新编码

r - 目录问题,无法安装 RStudio Server Packages Ubuntu

php - 如何从 mysql url 中提取文件夹名称并删除它及其所有内容?

android - 网址打开连接

java - 如何制作基于 Java 的图标 URL

r - 列表列表(来自 API 调用)到 R 中的数据框

python - 根据子字符串拆分列表元素

在不规则时间序列上滚动窗口

r - 使用 R 中的 dplyr 查找分组观察的比例

r - 查找一组字符串中子字符串的频率