0

我有一个数据框

> df
  letters numbers
1       A       1
2       B       2
3       C       3
4       D       4
5       E       5

并希望在连接行后得到以下结果:

"A1","B2","C3","D4","E5"

为了获得以下内容:

c("A1","B2","C3","D4","E5")

以下代码有什么问题?

> paste(df$letters, df$numbers, sep="",collapse='","')
[1] "A1\",\"B2\",\"C3\",\"D4\",\"E5"
4

4 回答 4

3

对于 a data.frame,您可能想尝试:

> do.call(paste0, df)
[1] "A1" "B2" "C3" "D4" "E5"

或者,如果您想要一个带逗号的字符串,请按如下方式修改您的方法:

> paste0(df$letters, df$numbers, collapse = ", ")
[1] "A1, B2, C3, D4, E5"

在那里获取报价具有欺骗性:

> paste0('"', paste0(df$letters, df$numbers, collapse = '", "'), '"')
[1] "\"A1\", \"B2\", \"C3\", \"D4\", \"E5\""

看起来有反斜杠,但没有:

> cat(paste0('"', paste0(df$letters, df$numbers, collapse = '", "'), '"'))
"A1", "B2", "C3", "D4", "E5"
> nchar(paste0('"', paste0(df$letters, df$numbers, collapse = '", "'), '"'))
[1] 28

或者,也许您正在寻找dQuotesQuote或者shQuote(很难说不知道为什么要做您正在做的事情):

> noquote(paste(dQuote(paste0(df$letters, df$numbers)), collapse = ", "))
[1] “A1”, “B2”, “C3”, “D4”, “E5”
> noquote(paste(shQuote(paste0(df$letters, df$numbers)), collapse = ", "))
[1] 'A1', 'B2', 'C3', 'D4', 'E5'
> noquote(paste(sQuote(paste0(df$letters, df$numbers)), collapse = ", "))
[1] ‘A1’, ‘B2’, ‘C3’, ‘D4’, ‘E5’
于 2013-04-03T12:25:02.460 回答
1

是转义字符,\用于标识"R 在使用时在任何字符串周围打印print以及"在字符串本身中打印。为了摆脱\你可以使用'而不是". 此外,要'绕过字符串,也是第一个和最后一个,您可以sprintf结合使用paste

> paste(sprintf("'%s%s'", letters[1:10], 1:10), collapse = ",")
[1] "'a1','b2','c3','d4','e5','f6','g7','h8','i9','j10'"
于 2013-04-03T12:24:08.257 回答
1

R 读\""字符串中的 a。跑的时候cat(paste0(df$letters, df$numbers, sep="",collapse='","'),"\n")就知道了。

于 2013-04-03T12:32:17.540 回答
1

这是我的帽子:

theString <- paste0(sprintf("\"%s%i\"", df$letters, df$numbers), collapse = ",")

cat(theString)
# "A1","B2","C3","D4","E5"
于 2013-04-03T12:36:22.423 回答