【问题标题】:data frame string search in a custom function自定义函数中的数据框字符串搜索
【发布时间】:2018-09-05 01:04:39
【问题描述】:

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

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

【问题讨论】:

  • 为什么不让你的函数string= 输入"truck" 并避免引用/取消引用?我理解不必引用列名等的动机,但即使是 tidyverse stringr 包也不使用符号来表示存储在向量中的文本字符串。

标签: r string dataframe search


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 2022-01-03
    • 2013-08-14
    • 1970-01-01
    相关资源
    最近更新 更多