I would like to assign a multi-line string to a variable in R so that I can call the variable later.
When I try paste("line 1", "line 2", sep = "\n")
I get "line 1\nline 2"
.
When I try cat("line 1", "line 2", sep = "\n")
, I get the desired output, but this is output is not persistent (cat()
returns an object of type None
). The reason that I'm trying to use a multi-line string is that I need to send query results via a SMTP server (and the package sendmailR
) in the message body (not as an attachment).
Asked
Active
Viewed 3,299 times
4

Jubbles
- 4,450
- 8
- 35
- 47
1 Answers
11
paste("line 1", "line 2", sep = "\n")
is the right way, you get what you intended:
> a = paste("line 1", "line 2", sep = "\n")
> cat(a)
line 1
line 2>
Your confusion probably comes from the fact that print
escapes the output, so it is printing the string the way it would be expected by the parser:
> print(a)
[1] "line 1\nline 2"
Note the quotes around the string. cat
prints the output as-is. In both cases the object is the same, it's only the output format that differs.
Obviously, you could create the string directly without paste
:
> a = "line1\nline2"
> cat(a)
line1
line2>

Simon Urbanek
- 13,842
- 45
- 45
-
I will give your proposed solution a try tomorrow (when I have access to the SMTP server that I've been using), but I am a bit skeptical that it will work. My problem sounds similar to the following: http://stackoverflow.com/questions/6889862/sweave-rweavehtml-cat-output-does-not-appear-in-the-output . The function `cat()` doesn't seem persistent; when I try to pass it to the `msg` named argument in `sendmail()`, I receive an email with a blank body (and the `cat` expression is outputted to the console). – Jubbles Jan 31 '12 at 03:11
-
@Jubbles You do know that `cat` doesn't return a value, right? It sends the text to a file or connection. Make sure you try passing the raw character `"line1\nline2"` to the `msg` argument. – joran Jan 31 '12 at 03:32
-
@joran: I am aware that `cat` doesn't return a value. (`cat()` returns an object of type `None`). I'll try just passing the raw character. – Jubbles Jan 31 '12 at 03:34
-
1@Simon Urbanek: My skepticism proved unwarranted. I tried the following code `d <- "part1\tpart2\npart3\tpart4"` with `sendmail(to = 'test1@example.com', from = 'test2@example.com', subject = 'Test', msg = d, control = list(smtpServer = 'mailhost.example.com', smtpPort = 25))` and it worked. Thank you very much. – Jubbles Jan 31 '12 at 14:42