brad-cannell / r4epi

Repository for the R for Epidemiology book
http://www.r4epi.com/
Other
21 stars 51 forks source link

Show them how to work with paste better #152

Open mbcann01 opened 6 months ago

mbcann01 commented 6 months ago

Here's the stuff I cut from the working with character vectors chapter:

paste(8, "(", 0.67, ")")
paste0(8, "(", 0.67, ")")

If you pass several vectors to paste0, they are concatenated in a vectorized way.

(nth <- paste0(1:12, c("st", "nd", "rd", rep("th", 9))))

paste works the same, but separates each input with a space. Notice that the recycling rules make every input as long as the longest input.

paste(month.abb, "is the", nth, "month of the year.")

You can change the separator by passing a sep argument, which can be multiple characters.

paste(month.abb, "is the", nth, "month of the year.", sep = "_*_")

To collapse the output into a single string, pass a collapse argument.

paste0(nth, collapse = ", ")

For inputs of length 1, use the sep argument rather than collapse

paste("1st", "2nd", "3rd", collapse = ", ") # probably not what you wanted
paste("1st", "2nd", "3rd", sep = ", ")

You can combine the sep and collapse arguments together.

paste(month.abb, nth, sep = ": ", collapse = "; ")
ehr %>% 
  select(starts_with("name")) %>% 
  mutate(name_full = paste(name_last, name_first, sep = ", "))