根据列中以逗号分隔的多个值过滤数据

时间:2021-07-19 05:21:43

标签: r dplyr

需要从表中过滤数据,我有一个输入表如下

export class AlarmComponent implements OnInit{
dateFormGroup = new FormGroup({});

constructor(){
    this.dateFormGroup =  new FormGroup({
      dateTimeSelected: new FormControl()
    });
  }
  resetFilters(): any {
    console.log(this.dateFormGroup.value.dateTimeSelected);
    this.dateFormGroup.value.dateTimeSelected = null;
    this.dataSource.filter = '';
    this.todoService.getAlerts(this.currentSensorId).subscribe((response: any) => {
      this.tableData = [];
      this.dateTimeArr = [];
      for (let i = 0; i < response.alertResponses.length; i++) {
        this.tableData.push(response.alertResponses[i]);
        this.dateTimeArr.push(moment(response.alertResponses[i].dated).format('YYYY-MM-DD'));
        this.dateTimeArr = [...new Set(this.dateTimeArr)];
      }
    });
  }
}

我还有一个由逗号分隔的单个字符,如下所示:

Emp_id = c(121,122,191,181,277,333)  
salary = c(7838,8389,8940,9491,10042,10593)  
Country = c("USA","USA","UK","USA","UK","USA")

df = data.frame(Emp_id,salary,Country)

现在,我需要根据 Emp_lst = "121,191,181" 中的值过滤 df 行。为此,我尝试了下面的代码,但我得到了 0 行

Emp_lst

以上代码需要修改吗?

4 个答案:

答案 0 :(得分:0)

我们可以在此处使用基于正则表达式的方法,将您的员工 ID CSV 列表转换为替代:

length

数据:

regex <- paste0("^(?:", gsub(",", "|", Emp_lst, fixed=TRUE), ")$")
df[grepl(regex, df$Emp_id), ]

  Emp_id salary Country
1    121   7838     USA
3    191   8940      UK
4    181   9491     USA

答案 1 :(得分:0)

Emp_id <- c(121,122,191,181,277,333) salary <- c(7838,8389,8940,9491,10042,10593) Country <- c("USA","USA","UK","USA","UK","USA") df <- data.frame(Emp_id,salary,Country) Emp_lst <- "121,191,181" 改为 Emp_lst = "121,191,181"

Emp_lst = c(121,191,181)

答案 2 :(得分:0)

你可以这样做:

  1. unlist Emp_lst 使用 strsplit 访问所有 3 个号码
  2. filter_all 用作 filter 的变体
library(dplyr)
Emp_lst <- unlist(strsplit(Emp_lst,","))
filter_all(df, any_vars(. %in% Emp_lst))

输出:

  Emp_id salary Country
1    121   7838     USA
2    191   8940      UK
3    181   9491     USA

答案 3 :(得分:0)

您可以用逗号分隔 Emp_lst 并选择 Emp_id 匹配的行。

Emp_lst = "121,191,181"
subset(df, Emp_id %in% strsplit(Emp_lst, ',\\s*')[[1]])

#  Emp_id salary Country
#1    121   7838     USA
#3    191   8940      UK
#4    181   9491     USA
相关问题