在R中使用grep从数据框中删除行 [英] Using grep in R to delete rows from a data.frame
问题描述
d< - data.frame(cbind(x = y = 1:10,z = c(苹果,梨,香蕉,A,B,C,D,E,F ),stringsAsFactors = FALSE)
我想从这个数据框中删除一些行,具体取决于列z的内容:
new_d< - d [-grep(D,d $ z),]
这工作正常;第7行现在已被删除:
new_d
xyz
1 1 1 apple
2 1 2梨
3 1 3香蕉
4 1 4 A
5 1 5 B
6 1 6 C
8 1 8 E
9 1 9 F
10 1 10 G
但是,当我使用grep搜索不存在的内容在列z中,似乎删除数据框的所有内容:
new_d< - d [-grep(K ,d $ z),]
new_d
[1] xyz
< 0 rows> (或0长度行)
我想在这个或另一个中搜索和删除行方式,即使我正在搜索的字符串不存在。如何解决这个问题?
您可以使用TRUE / FALSE子集而不是数字。
grepl
像grep一样,但它返回一个逻辑
矢量。
d [!grepl(K,d $ z),]
xyz
1 1 1苹果
2 1 2梨
3 1 3香蕉
4 1 4 A
5 1 5 B
6 1 6 C
7 1 7 D
8 1 8 E
9 1 9 F
10 1 10 G
I have a dataframe such as this one:
d <- data.frame(cbind(x=1, y=1:10, z=c("apple","pear","banana","A","B","C","D","E","F","G")), stringsAsFactors = FALSE)
I'd like to delete some rows from this dataframe, depending on the content of column z:
new_d <- d[-grep("D",d$z),]
This works fine; row 7 is now deleted:
new_d
x y z
1 1 1 apple
2 1 2 pear
3 1 3 banana
4 1 4 A
5 1 5 B
6 1 6 C
8 1 8 E
9 1 9 F
10 1 10 G
However, when I use grep to search for content that is not present in column z, it seems to delete all content of the dataframe:
new_d <- d[-grep("K",d$z),]
new_d
[1] x y z
<0 rows> (or 0-length row.names)
I would like to search and delete rows in this or another way, even if the character string I am searching for is not present. How to go about this?
You can use TRUE/FALSE subsetting instead of numeric.
grepl
is like grep, but it returns a logical
vector. Negation works with it.
d[!grepl("K",d$z),]
x y z
1 1 1 apple
2 1 2 pear
3 1 3 banana
4 1 4 A
5 1 5 B
6 1 6 C
7 1 7 D
8 1 8 E
9 1 9 F
10 1 10 G
这篇关于在R中使用grep从数据框中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!