Spruce Island
Spruce Island

Reputation: 445

paste text with a newline/return in formatted text

I want to do a column that is formatted to use for a mailing address and I can not get the newline/return carriage or <br/> to work when making a new column.

name = c("John Smith", "Patty Smith", "Sam Smith")
address = c("111 Main St.", "222 Main St.", "555 C Street")
cityState = c("Portland, OR 97212", "Portland, OR 95212", "Portland, OR 99212")
df <- data.frame(name, address, cityState)

I want to create a column that formats the data in an address label: John Smith 111 Main st. Portland, OR 97212

Each new column: will have a return after each line: so it is always 3 lines. One line for each of the other 3 columns.

# example of what I am trying to do... 
paste0(name, "return", address, "return", cityState).  Everything I have tried does not work for making a newline.

Upvotes: 28

Views: 96792

Answers (2)

alistaire
alistaire

Reputation: 43344

You need to paste it together with a newline (\n) separator. To assemble it from df,

addresses <- apply(df, 1, paste, collapse = '\n')

If you print it normally, it will show you the \n characters:

addresses
## [1] "John Smith\n111 Main St.\nPortland, OR 97212" 
## [2] "Patty Smith\n222 Main St.\nPortland, OR 95212"
## [3] "Sam Smith\n555 C Street\nPortland, OR 99212"  

To print with the newlines evaluated use cat, also with sep = '\n' to insert line breaks between items:

cat(addresses, sep = '\n')
## John Smith
## 111 Main St.
## Portland, OR 97212
## Patty Smith
## 222 Main St.
## Portland, OR 95212
## Sam Smith
## 555 C Street
## Portland, OR 99212

Upvotes: 12

csgillespie
csgillespie

Reputation: 60462

To get a new line (or return) we use \n. So

addr = paste(name,  address, cityState, sep="\n")

To view the result just use cat

> cat(addr[1])
#John Smith
#111 Main St.
#Portland, OR 97212

The function cat just prints to the screen.


The other standard character is \t for a tab-space.

Upvotes: 35

Related Questions