Difference between paste() and paste0()

前端 未结 3 1743
隐瞒了意图╮
隐瞒了意图╮ 2021-01-31 08:16

Being new to R, can someone please explain the difference between paste() and paste0(), what I had understood from some post is that

p         


        
相关标签:
3条回答
  • 2021-01-31 08:28

    In simple words,

    paste() is like concatenation using separation factor, whereas,

    paste0() is like append function using separation factor.

    Adding some more references to above discussion, below try outs can be useful to avoid confusion:

    > 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-"
    
    0 讨论(0)
  • 2021-01-31 08:30

    Let me put it in a simple words.. paste0 will automatically exclude the space in your concatenation..

    For Example, I want to create a Training and test path..here's the code..

    > 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"
    
    0 讨论(0)
  • 2021-01-31 08:46

    As explained 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

    0 讨论(0)
提交回复
热议问题