Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
输入字符向量的R函数_R_Function - Fatal编程技术网

输入字符向量的R函数

输入字符向量的R函数,r,function,R,Function,我目前有10个向量,如下所示: string1 <- c("house", "home", "cabin") string2 <-c("hotel", "hostel", "motel") string1如果您需要函数,可以尝试: fun1 <- function(namePrefix, dat){ #assuming that the datasets have a common prefix i.e. `string` pat <- paste0("^", name

我目前有10个向量,如下所示:

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

string1如果您需要函数,可以尝试:

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

试试
nm1
sapply(c(string1,string2),grep,x=a$Contents,value=TRUE)
你能评论一下这是如何工作的吗?我在envir=@user3813578迷路了。在这里,我假设向量对象名称都以前缀
string
开头,后跟一些
数字
。所以我用了一行
pat
a <- read.table(text='Contents     other
1     "a house a home"     "111"
2     "cabin in the woods"     "121"', header=TRUE)
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