Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert character at end of string in R, except for the last element

Tags:

r

I looked but failed to find an answer to how to add a character to the end of each and every element in a string vector in R, except the last one...

Consider the following:

data <- c("cat", "dog", "mouse", "lion")

I'd like to apply a function that pastes a "," at the end of each element such that the result is:

[1] "cat,", "dog,", "mouse,", "lion"

apply functions? for loop? any help is appreciated...

like image 403
gh0strider18 Avatar asked Jan 19 '15 15:01

gh0strider18


2 Answers

You can do this in a couple of ways:

  1. Subset the 'data' without the last element, paste ,, and assign that to the original data (without last element)

    data[-length(data)] <- paste0(data[-length(data)], ',')
    
  2. Use strsplit after collapsing it as a string

    strsplit(paste(data, collapse=', '), ' ')[[1]]     
    
like image 133
akrun Avatar answered Nov 10 '22 13:11

akrun


I know this is an old question, but since I suppose people (like me) still end here, they may want to consider easy solutions offered by more recent but fairly common packages. They offer slightly different options.

Option 1: Knitr

data <- c("cat", "dog", "mouse", "lion")
knitr::combine_words(data, before = '`')

# `cat`, `dog`, `mouse`, and `lion`

Option 2: Glue

data <- c("cat", "dog", "mouse", "lion")
glue::glue_collapse(x = data, ", ", last = " and ")

# cat, dog, mouse and lion
like image 39
giocomai Avatar answered Nov 10 '22 14:11

giocomai