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

I looked, but could not find an answer on how to add a character to the end of each element in a row vector in R , except for the last ...

Consider the following:

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

I would like to apply a function that inserts a "," at the end of each element in such a way that the result is:

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

apply functions? for the cycle? any help is appreciated ...

+7
r
source share
1 answer

You can do this in several ways:

  • Adjust the β€œdata” without the last element, insert , and assign it to the original data (without the last element)

     data[-length(data)] <- paste0(data[-length(data)], ',') 
  • Use strsplit after folding it as a string

     strsplit(paste(data, collapse=', '), ' ')[[1]] 
+9
source share

All Articles