删除包含特定数据的行

时间:2013-08-12 02:40:01

标签: r dataframe

在我的数据框中,第一列是一个因素,我想删除具有特定值 factorname 的行(当值存在时)。我试过了:

df <- df[-grep("factorname",df$parameters),]

当目标因子名称存在时,哪种方法很有效。但是,如果 factorname 不存在,则此命令会破坏数据帧,使其保留0行。所以我试过了:

df <- df[!apply(df, 1, function(x) {df$parameters == "factorname"}),]

不会删除违规行。如果 factorname 存在,我如何测试 factorname 的存在并删除该行?

2 个答案:

答案 0 :(得分:6)

您可以使用:

df[ which( ! df$parameter %in% "factorname") , ]

(使用%in%,因为它可以更好地推广到多个排除标准。)也可能:

df[ !grepl("factorname", df$parameter) , ]

答案 1 :(得分:2)

l<-sapply(iris,function(x)is.factor(x)) # test for the factor variables
>l
Sepal.Length  Sepal.Width Petal.Length  Petal.Width      Species 
       FALSE        FALSE        FALSE        FALSE         TRUE 

m<-iris[,names(which(l=="TRUE"))]) #gives the data frame of factor variables only
iris[iris$Species !="setosa",] #generates the data with Species other than setosa 



   > head(iris[iris$Species!="setosa",])
   Sepal.Length Sepal.Width Petal.Length Petal.Width    Species
51          7.0         3.2          4.7         1.4 versicolor
52          6.4         3.2          4.5         1.5 versicolor
53          6.9         3.1          4.9         1.5 versicolor
54          5.5         2.3          4.0         1.3 versicolor
55          6.5         2.8          4.6         1.5 versicolor
56          5.7         2.8          4.5         1.3 versicolor