R function to input character vector

I currently have 10 vectors that look like the following:

string1 <- c("house", "home", "cabin")
string2 <-c("hotel", "hostel", "motel")

and so on for 10 strings.

R newbie learning functions. I have the following code I want to execute across these 10 strings, and turn in to a function. This code takes in these strings and searches for matches and creates a new variable:

a$string.i <- (1:nrow(a) %in% c(sapply(string1, grep, a$Contents, fixed = TRUE))) +0

As I am new to R, I'm stumped on how to turn this into a function. Do I need to first define the number of strings, then set 'string1' in the above code to x? How do I set the name of the variable = to the name of the string?

Some sample data:

a <- read.table(text='Contents     other
1     "a house a home"     "111"
2     "cabin in the woods"     "121"', header=TRUE)

Answers


If you need a function, may be you can try:

fun1 <- function(namePrefix, dat){ #assuming that the datasets have a common prefix i.e. `string`
pat <- paste0("^", namePrefix, "\\d")
nm1 <- ls(pattern=pat, envir=.GlobalEnv)
lst <- mget(nm1, envir=.GlobalEnv)
lst2 <- lapply(lst, function(x) 
      (1:nrow(dat) %in% c(sapply(x, grep, dat$Contents, fixed=TRUE)))+0) #your code
dat[names(lst2)] <- lst2
dat

}

 fun1("string", a)
 #            Contents other string1 string2
 #1     a house a home   111       1       0
 #2 cabin in the woods   121       1       0

Need Your Help

To Show A Country Map Using Google Maps API

google-maps

Can I display a Country's Map passing the country name as parameter to Google Maps API?

os.path.join not finding file in specified directory

python python-3.x pygame

I'm working on a game and have a function that checks for valid audio files before attempting to load them. The function looks like this:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.