这是以下线程的延续:
Creating Binary Identifiers Based On Condition Of Word Combinations For Filter
预期输出与所述线程相同。
我现在正在编写一个函数,它可以将动态名称作为变量。
这是我的目标代码,如果我要手动运行它:
df <- df %>% group_by(id, date) %>% mutate(flag1 = if(eval(parse(text=conditions))) grepl(pattern, item_name2) else FALSE)为了使它考虑到动态变量名称,我一直在这样做:
groupcolumns <- c(id, date)
# where id and date will be entered into the function as character strings by the user
variable <- list(~if(eval(parse(text=conditions))) grepl(pattern, item) else FALSE)
# converting to formula to use with dynamically generated column names
# "conditons" being the following character vector, which I can automatically generate:
conditons <- "any(grepl("Alpha", Item)) & any(grepl("Bravo", Item))"这将成为:
df <- df %>% group_by_(.dots = groupcolumns) %>% mutate_(.dots = setNames(variable, flags[1]))
# where flags[1] is a predefined vector of columns names that I have created
flags <- paste("flag", seq(1:100), sep = "")问题是,我无法对grepl函数做任何事情;动态地指定"item“。如果我这样做了,作为"df$item",并做了eval(解析(text=“df$item”)),管道的意图就会失败,因为我正在做一个group_by_,它会导致一个错误(自然)。这也适用于我设定的条件。
是否存在一种让grepl使用动态变量名的方法?
非常感谢你(尤其是阿克龙)!
编辑1:
尝试了以下操作,现在将项的名称传递给grepl没有问题。
variable <- list(~if(eval(parse(text=conditions))) grepl(pattern, as.name(item)) else FALSE)然而,问题在于管道似乎无法工作,因为as.name(item)的输出被看作是环境中不存在的对象。
编辑2:
在dplyr中尝试do():
variable <- list(~if(eval(parse(text=conditions))) grepl(pattern, .$deparse(as.name(item))) else FALSE)
df <- df %>% group_by_(.dots = groupcolumns) %>% do_(.dots = setNames(variable, combiflags[1])) 这给我带来了一个错误:
Error: object 'Item' not found 发布于 2017-01-24 22:22:40
如果我正确理解了您的问题,您希望能够在grepl中动态地输入模式和这些模式要搜索的对象吗?您的最佳解决方案将完全取决于您选择如何存储模式和如何选择存储要搜索的对象。不过,我有一些想法应该对你有帮助。
对于动态模式,尝试使用粘贴函数输入一个模式列表。这将允许您一次搜索许多不同的模式。
grepl(paste(your.pattern.list, collapse="|"), item)假设您想要设置一个场景,其中您要在目录中存储许多感兴趣的模式。可能是从服务器或其他输出自动收集的。如果模式位于单独的文件中,则可以使用以下方法创建模式列表:
#set working directory
setwd("/path/to/files/i/want")
#make a list of all files in this directory
inFilePaths = list.files(path=".", pattern=glob2rx("*"), full.names=TRUE)
#perform a function for each file in the list
for (inFilePath in inFilePaths)
{
#grepl function goes here
#if each file in the folder is a table/matrix/dataframe of patterns try this
inFileData = read_csv(inFilePath)
vectorData=as.vector(inFileData$ColumnOfPatterns)
grepl(paste(vectorData, collapse="|"), item)
}对于动态指定项,可以使用几乎相同的框架。
#set working directory
setwd("/path/to/files/i/want")
#make a list of all files in this directory
inFilePaths = list.files(path=".", pattern=glob2rx("*"), full.names=TRUE)
#perform a function for each file in the list
for (inFilePath in inFilePaths)
{
#grepl function goes here
#if each file in the folder is a table/matrix/dataframe of data to be searched try this
inFileData = read_csv(inFilePath)
grepl(pattern, inFileData$ColumnToBeSearched)
}如果这与您所设想的太远,请更新您的问题,详细说明您使用的数据是如何存储的。
https://stackoverflow.com/questions/41215780
复制相似问题