以“A1”,“B2”,“C3”形式连接行

时间:2013-04-03 12:19:56

标签: string r paste

我有一个数据框

> 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 个答案:

答案 0 :(得分:3)

对于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

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

> 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’

答案 1 :(得分:1)

\是转义字符,用于标识",当在字符串本身中使用print"时,R会在任何字符串周围打印。要摆脱\,您可以使用'代替"。另外,要在字符串周围获取',也可以使用sprintfpaste结合使用{<1}}:

> paste(sprintf("'%s%s'", letters[1:10], 1:10), collapse = ",")
[1] "'a1','b2','c3','d4','e5','f6','g7','h8','i9','j10'"

答案 2 :(得分:1)

R在字符串中将\"读作"。当你运行cat(paste0(df$letters, df$numbers, sep="",collapse='","'),"\n")时,你会看到。

答案 3 :(得分:1)

这是我的帽子:

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

cat(theString)
# "A1","B2","C3","D4","E5"