histelheim
histelheim

Reputation: 5088

Avoiding repetition in R

Here is a typical problem that I have:

replace_letters <- function(string){
  gsub("x", "a", string)
}

string_x_new <- replace_letters("string_x")
string_y_new <- replace_letters("strxng_y")
string_z_new <- replace_letters("xstring_z")
...

Meaning that I'm writing a function (the function in the example is arbitrary) and then I want to apply that to an arbitrary set of objects. What is a neater way of doing this without having to repeat the function multiple times (sometimes I have long lists of 10-15 calls to the same function for different objects)?

Upvotes: 0

Views: 304

Answers (3)

johannes
johannes

Reputation: 14433

You can make use of R's vectorization:

strings<-c("string_x", "strxng_y", "xstring_z")
replace_letters(strings)
## [1] "string_a"  "strang_y"  "astring_z"

Upvotes: 1

anon
anon

Reputation:

You can create a vectors of the objects you'd like to apply the function to. Let's take your example:

new.strings <- sapply(c("string_x", "string_y", "string_z"), replace_letters)

Upvotes: 1

C_Z_
C_Z_

Reputation: 7796

Put your strings in a vector using c("string_x", "strxng_y", "xstring_z") then use an apply function Example:

strings<-c("string_x", "strxng_y", "xstring_z")

replace_letters <- function(string){
  gsub("x", "a", string)
}

strings <- sapply(strings, replace_letters)

Upvotes: 3

Related Questions