r - 自定义函数中的数据框字符串搜索
问题描述
我正在尝试编写一个在数据框中搜索给定字符串的函数。例如:
# Set up
library(tidyverse)
options(stringsAsFactors= F)
color <- c('black', 'black', 'blue', 'blue', 'yellow')
vehicle <- c('truck', 'truck', 'car', 'car', 'bike')
plant <- c('tree', 'flower', 'grass', 'tree', 'flower')
height <- c('tall', 'medium', 'short', 'tall', 'medium')
testdf <- as.data.frame(cbind(color, vehicle, plant, height))
创建一个函数来搜索任何行中具有卡车值的任何变量:
search.func <- function(df) {
names(df %>%
select_if(is.character) %>%
select_if(grepl('truck', .)))
}
search.func(testdf) # returns the correct result - 'vehicle'
为了使函数更灵活,并且能够传递任何字符串,我尝试过:
search.func2 <- function(df, string) {
string <- enquo(string)
names(df %>%
select_if(is.character) %>%
select_if(grepl(string, .)))
}
search.func2(testdf, truck) # errors out
但我没有正确使用 enquo - 我需要 grepl 函数中的引号,我无法告诉 R 如何去做。任何帮助表示赞赏!谢谢!
解决方案
添加后quo_name
你应该没问题。
search.func2 <- function(df, string) {
string <- enquo(string)
string <- quo_name(string)
names(df %>%
select_if(is.character) %>%
select_if(grepl(string, .)))
}
#search.func2(testdf, truck)
#[1] "vehicle"
推荐阅读
- javascript - 如何在此图表中添加“画笔 + 焦点”?
- amazon-web-services - API 网关输入验证 - 不允许额外的属性
- git - Git 暂时删除一些代码以获得更清晰的拉取请求
- python-3.x - discord.py 任务不起作用“命令”对象没有属性“开始”
- flutter - BLoC 在每个事件之后返回相同的数据
- typescript - 我可以将 jtd 粘贴为打字稿类型语法吗?
- amazon-web-services - 如何解决 AWS Cloudfront EC2 实例上的 504 错误
- python - OpenCV Homography 给出错误:输入数组应该至少有
- javascript - 如何在反应中使用 google-map-react 制作静态地图?
- xml - 如何使用 XSL 复制节点并更改其(原始和重复的)嵌套子节点的值?