在r中将三个变量值连接成单个值

时间:2014-06-27 15:20:25

标签: r

我有三个变量。我的目的是将三个变量连接成一个变量 为此,我使用cat函数来连接三个变量,但它正确地显示了值,但我在值之间得到了空格。在进行连接时,我不希望在值之间留有空格。

3 个答案:

答案 0 :(得分:2)

比@Duna的建议更简洁如下:

## @Duna's sample data
dd = data.frame(x = letters[1:5], y = 1:5, 
                z = c("this", "could", "work", "for", "you!"))

do.call(paste0, dd)
# [1] "a1this"  "b2could" "c3work"  "d4for"   "e5you!" 

以下内容也适用:

do.call(paste, c(dd, sep = ""))
with(dd, paste(x, y, z, sep = ""))
with(dd, paste0(x, y, z))

而且,对于多样性:

with(dd, sprintf("%s%s%s", x, y, z))

答案 1 :(得分:1)

你也可以使用:

 as.character(interaction(dd,sep=""))
 #[1] "a1this"  "b2could" "c3work"  "d4for"   "e5you!" 

paste2来自library(qdap)

 library(qdap)
 paste2(dd,sep="")
 #[1] "a1this"  "b2could" "c3work"  "d4for"   "e5you!" 

答案 2 :(得分:0)

尝试使用 Ananda 建议! 假设你有:

dd = data.frame(x = letters[1:5], y = 1:5, z = c("this", "could", "work", "for", "you!"))

dd

  x y     z
1 a 1  this
2 b 2 could
3 c 3  work
4 d 4   for
5 e 5  you!

然后

dd$w = paste(dd$x, paste(dd$y, dd$z, sep=""),sep="")

所以你得到了

dd
  x y     z       w
1 a 1  this  a1this
2 b 2 could b2could
3 c 3  work  c3work
4 d 4   for   d4for
5 e 5  you!  e5you!