我正在使用 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/