【发布时间】:2016-03-24 16:30:57
【问题描述】:
我的问题的核心是使用“粘贴”将变量放入正则表达式中,并使用转义字符作为引号。这是其他 stackoverflow 问题的答案——但它似乎不起作用。我认为这个问题的独特之处在于它结合了这两个元素——使用粘贴将变量放入正则表达式,并使用转义字符作为引号。我也尝试过使用“cat”,这是另一个常见的答案,但没有成功。
我正在尝试做的是通过包含数千个名称的列表更轻松地按名称进行过滤。 (我正在从可视化软件 (Spotfire) 迁移到 R,但我错过了列表框过滤器。)我会很高兴收到有关如何执行此任务的任何建议。
而且,是的,我是 R 编程(以及一般编程)的新手。Stackoverflow 一直是最好的资源。你们一定是一群天才,
谢谢--
# mtcars example for filtering and finding names for the stack overflow question
data(mtcars)
# make the data match my dataframe, where I don't have row names but have a column with the name
mtcars$carname <- NA #declare the variable
mtcars$carname <- rownames(mtcars) #assign the names to a column
findcar <- function() {
while(TRUE) {
print("Type the car's name:")
apxname <- readline() #approx name
#type in Merc for this example
carlst <- mtcars$carname[(grepl("(apxname)",mtcars$carname, ignore.case = TRUE))] #list of cars that matches the approximate name
# if I type . . . (grepl("(Merc)", mtcars$carname, . . . )) it works great
#So per other stackoverflow responses, I've tried using "paste" or "paste0" without success
#I can't get this to work
#carlst <- mtcars$carname[(grepl(paste0('\"(',apxname, ')\"', sep=""),mtcars$carname, ignore.case = TRUE))]
print("Here's the list of similar customers:")
print(carlst)
print("Type the number of your car:")
carnum <- readline() #car number
therightone <- carlst[as.numeric(carnum)]
paste("You selected",therightone,"Is this the car (Y/N)?", sep=" ")
carconf <- readline() #car confirmation
if(carconf == "Y") break)
}
return(therightone)
}
【问题讨论】:
-
请扩展“但它似乎不起作用”。谢谢。
-
使用
carlst <- mtcars$carname[(grepl(get("apxname"), x = mtcars$carname, ignore.case = TRUE))]。 -
我不能编辑这个,因为它只是一个字符,但你还必须删除
break语句后面的括号。 -
你不需要或不想要引号;您需要评估该变量。您也不需要
grepl的括号;无论如何,它都会匹配一切。您可能需要在其后添加paste和$以指示行尾,这样您就可以区分Mazda RX4和Mazda RX4 Wag之类的内容。一般来说,你需要类似grepl(paste0('Mazda RX4', '$'), rownames(mtcars)) -
@alistaire OP 似乎希望用户首先选择一个汽车品牌(基于模糊匹配),然后为他提供所有可能的选择,以便从选项列表中选择精确匹配。所以不需要区分不同的模型。