我经常从一个数据库中获取数据集,在这个数据库中,测试概要文件是以“假冒伪劣”的名字创建的,我决定编写一个函数来提取包含这些测试用例(假用例)的行。
下面是我收到的数据类型的一个示例。让我们将此数据帧称为names
FirstName<-c("Alan","James","Miles","Nath")
LastName<-c("Bottom","Bogus","Davis","Gun")
names<-data.frame(FirstName,LastName)
FirstName LastName
Alan Bottom
James Bogus
Miles Davis
Nath Gun我创建了一个名为bogusfun的函数,如下所示
bogusfun<-function(df){
if(any(grepl("Bogus",df))) # This is to see which column contains "Bogus" profiles
col<-(colnames(df[grepl("Bogus",df)])) # This line assigns the column name containing the Bogus profile
col<-as.name(col)
library(dplyr)
df<-df%>%
filter(col!="Bogus")
return(df)
}当我在dataframe上运行这个函数时
bogusfun(names)
我希望能看到
FirstName LastName
Alan Bottom
Miles Davis
Nath Gun然而,它并不像预期的那样起作用。因此,我看了下面的代码部分
if(any(grepl("Bogus",names)))
col<-colnames(names[grepl("Bogus",names)])
col<-as.name(col)
df<-df%>%
filter(col="Bogus")并给出了UseMethod("filter_") : no applicable method for 'filter_' applied to an object of class "function"中的误差。
发布于 2020-05-05 20:15:09
在这里,我们可以使用filter_all
library(dplyr)
names %>%
filter_all(all_vars(. != 'Bogus'))
# FirstName LastName
#1 Alan Bottom
#2 Miles Davis
#3 Nath Gun或使用filter/across
names %>%
filter(across(everything(), ~ . != 'Bogus'))
# FirstName LastName
#1 Alan Bottom
#2 Miles Davis
#3 Nath Gun在OP的函数中,grep被应用于整个数据集,而grep则在vector/matrix上工作。根据?grep
x,文本-一个寻找匹配的字符向量,或者一个可以被as.character胁迫到字符向量的对象。支持长向量。
https://stackoverflow.com/questions/61622022
复制相似问题