首页 > 解决方案 > 自定义函数中的数据框字符串搜索

问题描述

我正在尝试编写一个在数据框中搜索给定字符串的函数。例如:

# 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 如何去做。任何帮助表示赞赏!谢谢!

标签: rstringdataframesearch

解决方案


添加后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"

推荐阅读