Reputation: 1114
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)
Upvotes: 0
Views: 3631
Reputation: 887018
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
Upvotes: 1