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='')
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.
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.
To concatenate strings in r programming, use paste() function. The syntax of paste() function that is used to concatenate two or more strings.
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.
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>
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With