You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言编写支持字符/数值输入的数据框state参数过滤函数

R语言多规则过滤自定义函数实现

完整实现代码

tidyverse版本(兼容原代码的%>%写法)

library(dplyr)
library(stringr)

filter_state <- function(df, state) {
  # 数值输入逻辑:过滤state_rank≤输入值的行
  if (is.numeric(state)) {
    return(df %>% filter(state_rank <= state))
  }
  # 字符输入逻辑:拆分逗号分隔的州编码后匹配
  if (is.character(state)) {
    target_states <- str_split(state, ",", simplify = T) %>% str_trim()
    return(df %>% filter(state_code %in% target_states))
  }
  # 非法输入提示
  stop("state参数仅支持数值、字符两类输入")
}

无依赖base R版本

filter_state <- function(df, state) {
  if (is.numeric(state)) {
    return(df[df$state_rank <= state, ])
  }
  if (is.character(state)) {
    target_states <- trimws(strsplit(state, ",")[[1]])
    return(df[df$state_code %in% target_states, ])
  }
  stop("state参数仅支持数值、字符两类输入")
}

功能测试示例

  • 数值输入测试:filter_state(df.sample, 2),返回所有state_rank≤2的6条记录
  • 单州字符输入测试:filter_state(df.sample, "AZ"),返回州编码为AZ的3条记录
  • 多州逗号分隔输入测试:filter_state(df.sample, "WA,MO"),返回WA、MO对应的2条记录

逻辑说明

  • 先判断state参数的类型,分支执行不同过滤规则
  • 字符输入场景自动拆分逗号分隔的多州编码,同时自动去除编码前后的空格,兼容"AZ,CA"、"AZ, CA"两类常见输入格式
  • 用%in%代替原代码的==做匹配,天然支持单个、多个州编码的过滤需求
  • 增加非法输入的报错提示,避免参数传错时出现不可预期的结果

内容的提问来源于stack exchange,提问作者Sharath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 12:15:04