r - 如何使用字符向量过滤数据框

标签 r filter dplyr

我正在尝试使用 filter() 过滤 data.frame包中的函数 dplyr .这里的主要问题是我想对条件使用向量。

例如

library(dplyr)
conditions <- c("Sepal.Width<3.2","Species==setosa")
DATA <- iris %>%
  filter(conditions) #This doesnt work, of course.


有什么功能需要
conditions <- c("Sepal.Width<3.2","Species==setosa")

作为输入并给我
Sepal.Width<3.2 & Species==setosa

作为输出?我想使用 eval(parse...)sapply也许 paste0()添加 & ,但不能让它工作。

任何帮助将不胜感激。

最佳答案

有多个问题。首先,您需要为第二个条件引用内引号:

conditions <- c("Sepal.Width < 3.2", "Species == 'setosa'")

然后,您需要指定两个条件之间的关联。在这里,我假设一个 & .那么你可以使用eval(parse(...)) :
iris %>%
 filter(eval(parse(text = paste(conditions, sep = "&"))))

   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1           5.1         3.5          1.4         0.2  setosa
2           4.9         3.0          1.4         0.2  setosa
3           4.7         3.2          1.3         0.2  setosa
4           4.6         3.1          1.5         0.2  setosa
5           5.0         3.6          1.4         0.2  setosa
6           5.4         3.9          1.7         0.4  setosa
7           4.6         3.4          1.4         0.3  setosa
8           5.0         3.4          1.5         0.2  setosa
9           4.4         2.9          1.4         0.2  setosa
10          4.9         3.1          1.5         0.1  setosa

另一方面,我认为引用 @Martin Mächler 总是很重要的。警告与此方法相关的潜在问题:

The (possibly) only connection is via parse(text = ....) and all good R programmers should know that this is rarely an efficient or safe means to construct expressions (or calls). Rather learn more about substitute(), quote(), and possibly the power of using do.call(substitute, ......).

关于r - 如何使用字符向量过滤数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58640343/

相关文章:

r - 尽管我在“描述”中使用了“导入”,但不需要命名空间依赖项错误

r - 使用R生成具有iid正态随机变量的矩阵

用于根据不均匀日期创建不均匀组的 R 函数

r - 如何根据字符串匹配选择 R 数据框中的列

r - 如何自动绘制具有相同行数和列数的多个 CSV 文件?

r - render()无法在容器化的Shiny应用中将.Rmd转换为.pdf

android - 如何将 InputFilter 应用于 EditTextPreferences?

ios - 我正在使用 CIFilter 获取模糊图像,但为什么输出图像总是大于输入图像?

Matlab 滤波器加速数据中的电尖峰

r - 筛选器变量,其列名包含模式