Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to paste a string on each element of a vector of strings using apply in R?

Tags:

r

apply

paste

I have a vector of strings.

d <- c("Mon","Tues","Wednes","Thurs","Fri","Satur","Sun") 

for which I want to paste the string "day" on each element of the vector in a way similar to this.

week <- apply(d, "day", paste, sep='') 
like image 475
pedrosaurio Avatar asked Aug 08 '11 15:08

pedrosaurio


People also ask

How do I add a string to a Vector in R?

Adding elements in a vector in R programming – append() method. append() method in R programming is used to append the different types of integer values into a vector in the last. Return: Returns the new vector after appending given value.

How do I paste a Vector into R?

You can use the paste() and paste0() functions in R to concatenate elements of a vector into a single string. The paste() function concatenates strings using a space as the default separator. The paste0() function concatenates strings using no space as the default separator.

How do I combine two strings in R?

To concatenate strings in r programming, use paste() function. The syntax of paste() function that is used to concatenate two or more strings.

How do I concatenate a character Vector in R?

The concatenation of vectors can be done by using combination function c. For example, if we have three vectors x, y, z then the concatenation of these vectors can be done as c(x,y,z). Also, we can concatenate different types of vectors at the same time using the same same function.


2 Answers

No need for apply(), just use paste():

R> d <- c("Mon","Tues","Wednes","Thurs","Fri","Satur","Sun") R> week <- paste(d, "day", sep="") R> week [1] "Monday"    "Tuesday"   "Wednesday" "Thursday"   [4] "Friday"    "Saturday"  "Sunday"    R>  
like image 183
Dirk Eddelbuettel Avatar answered Sep 19 '22 14:09

Dirk Eddelbuettel


Other have already indicated that since paste is vectorised, there is no need to use apply in this case.

However, to answer your question: apply is used for an array or data.frame. When you want to apply a function over a list (or a vector) then use lapply or sapply (a variant of lapply that simplifies the results):

sapply(d, paste, "day", sep="")         Mon        Tues      Wednes       Thurs         Fri       Satur     "Monday"   "Tuesday" "Wednesday"  "Thursday"    "Friday"  "Saturday"          Sun     "Sunday"  
like image 40
Andrie Avatar answered Sep 21 '22 14:09

Andrie