Print string and variable contents on the same line in R

前端 未结 8 1482
梦谈多话
梦谈多话 2020-12-07 07:35

Is there a way to print text and variable contents on the same line? For example,

wd <- getwd()
print(\"Current working dir: \", wd)

I c

相关标签:
8条回答
  • 2020-12-07 07:54

    Easiest way to do this is to use paste()

    > paste("Today is", date())
    [1] "Today is Sat Feb 21 15:25:18 2015"
    

    paste0() would result in the following:

    > paste0("Today is", date())
    [1] "Today isSat Feb 21 15:30:46 2015"
    

    Notice there is no default seperator between the string and x. Using a space at the end of the string is a quick fix:

    > paste0("Today is ", date())
    [1] "Today is Sat Feb 21 15:32:17 2015"
    

    Then combine either function with print()

    > print(paste("This is", date()))
    [1] "This is Sat Feb 21 15:34:23 2015"
    

    Or

    > print(paste0("This is ", date()))
    [1] "This is Sat Feb 21 15:34:56 2015"
    

    As other users have stated, you could also use cat()

    0 讨论(0)
  • 2020-12-07 07:57

    {glue} offers much better string interpolation, see my other answer. Also, as Dainis rightfully mentions, sprintf() is not without problems.

    There's also sprintf():

    sprintf("Current working dir: %s", wd)
    

    To print to the console output, use cat() or message():

    cat(sprintf("Current working dir: %s\n", wd))
    message(sprintf("Current working dir: %s\n", wd))
    
    0 讨论(0)
  • 2020-12-07 07:59

    The {glue} package offers string interpolation. In the example, {wd} is substituted with the contents of the variable. Complex expressions are also supported.

    library(glue)
    
    wd <- getwd()
    glue("Current working dir: {wd}")
    #> Current working dir: /tmp/RtmpteMv88/reprex46156826ee8c
    

    Created on 2019-05-13 by the reprex package (v0.2.1)

    Note how the printed output doesn't contain the [1] artifacts and the " quotes, for which other answers use cat().

    0 讨论(0)
  • 2020-12-07 07:59

    A trick would be to include your piece of code into () like this:

    (wd <- getwd())
    

    which means that the current working directory is assigned to wd and then printed.

    0 讨论(0)
  • 2020-12-07 08:02

    As other users said, cat() is probably the best option.

    @krlmlr suggested using sprintf() and it's currently the third ranked answer. sprintf() is not a good idea. From R documentation:

    The format string is passed down the OS's sprintf function, and incorrect formats can cause the latter to crash the R process.

    There is no good reason to use sprintf() over cat or other options.

    0 讨论(0)
  • 2020-12-07 08:14

    Or using message

    message("Current working dir: ", wd)
    

    @agstudy's answer is the more suitable here

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