paste() 和 paste0() 的区别

Difference between paste() and paste0()

作为 R 的新手,有人可以解释一下 paste()paste0() 之间的区别吗,我从一些 post 那里了解到

paste0("a", "b") === paste("a", "b", sep="")

连我都试过这样的东西

a <- c("a","b","c")
b <- c("y","w","q")
paste(a,b,sep = "_")
**output**
"a_y" "b_w" "c_q"

使用paste0()

a <- c("a","b","c")
b <- c("y","w","q")
paste0(a,b,sep = "_")
**output**
"ay_" "bw_" "cq_"

难道只是paste()在元素之间使用了分隔符而paste0()在元素之后使用了分隔符吗?

正如解释的那样in this blog by Tyler Rinker

paste has 3 arguments.

paste (..., sep = " ", collapse = NULL) The ... is the stuff you want to paste together and sep and collapse are the guys to get it done. There are three basic things I paste together:

  • A bunch of individual character strings.
  • 2 or more strings pasted element for element.
  • One string smushed together.

Here's an example of each, though not with the correct arguments

paste("A", 1, "%") #A bunch of individual character strings.

paste(1:4, letters[1:4]) #2 or more strings pasted element for element.

paste(1:10) #One string smushed together. Here's the sep/collapse rule for each:

  • A bunch of individual character strings – You want sep
  • 2 or more strings pasted element for element. – You want sep
  • One string smushed together.- Smushin requires collapse

paste0 is short for: paste(x, sep="") So it allows us to be lazier and more efficient.

paste0("a", "b") == paste("a", "b", sep="") ## [1] TRUE

让我用简单的话来说.. paste0 将自动排除您连接中的 space..

例如,我想创建一个训练和测试路径..这是代码..

> Curr_date=format(Sys.Date(),"%d-%b-%y")

> currentTrainPath = paste("Train_",Curr_date,".RData")

> currentTrainPath

[1] "Train_ 11-Jun-16 .RData"

> Curr_date=format(Sys.Date(),"%d-%b-%y")

> currentTrainPath = paste0("Train_",Curr_date,".RData")

> currentTrainPath

[1] "Train_11-Jun-16.RData"

简单来说,

paste() 就像使用分隔因子的串联, 而

paste0() 类似于使用分隔因子的追加函数。

为上面的讨论添加更多参考,下面的尝试可能有助于避免混淆:

> paste("a","b")  #Here default separation factor is " " i.e. a space

[1] "a b"  

> paste0("a","b") #Here default separation factor is "" i.e a null

[1] "ab"

> paste("a","b",sep="-")

[1] "a-b"

> paste0("a","b",sep="-")

[1] "ab-"

> paste(1:4,"a")

[1] "1 a" "2 a" "3 a" "4 a"

> paste0(1:4,"a")

[1] "1a" "2a" "3a" "4a"

> paste(1:4,"a",sep="-")

[1] "1-a" "2-a" "3-a" "4-a"

> paste0(1:4,"a",sep="-")

[1] "1a-" "2a-" "3a-" "4a-"