简体   繁体   English

删除r中包含全0的行

[英]Removing rows which contain all 0's in r

I have a file like this. 我有一个这样的文件。

"1" "4" "10" "ttts" 3
"2" "10" "22" "ttt" 2
"3" "10" "295" "00000" 13
"4" "10" "584" "0t000000" 5
"5" "10" "403" "000s" 15
"6" "10" "281" "000" 19
"7" "10" "123" "000q" 16
"8" "10" "127" "000" 20
........................

What I want is that all the rows which contains all 0 in the fourth column, such as the rows 3 and the rows 6 along with row 8 are eliminated. 我想的是,它包含所有的所有行0在第四列中,如行3和行6与排沿8被消除。 How can I do this in R? 我如何在R中做到这一点? Thanks! 谢谢!

Using grep is probably the most efficient way of doing this: 使用grep可能是最有效的方法:

data = read.table(header = TRUE, text = "  X2  X3       X4 X5
1  4  10     ttts  3
2 10  22      ttt  2
3 10 295    00000 13
4 10 584 0t000000  5
5 10 403     000s 15
6 10 281      000 19
7 10 123     000q 16
8 10 127      000 20")

data[!grepl("^0+$", data[,3]),]
#  X2  X3       X4 X5
#1  4  10     ttts  3
#2 10  22      ttt  2
#4 10 584 0t000000  5
#5 10 403     000s 15
#7 10 123     000q 16

Edit: Changed grep to grepl as per commenter's suggestions. 编辑:根据评论者的建议,将grep更改为grepl

I assume that row 8 should also be dropped. 我认为第8行也应该删除。

I would suggest trying the "stringi" package and doing something like this: 我建议尝试使用“ stringi”软件包并执行以下操作:

library(stringi)
stri_count_fixed(mydf[, 4], "0") == nchar(mydf[, 4])
# [1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

You can use this logical vector to subset from your original dataset. 您可以使用此逻辑向量从原始数据集中获取子集。


In base R, you can also try: 在基数R中,您还可以尝试:

vapply(strsplit(mydf[, 4], ""), function(x) all(x == "0"), logical(1L))
# [1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE

Another way would be: 另一种方法是:

indx <- as.numeric(as.character(data[,4])) #all the non-numeric elements coerced to NA

 data[!(!is.na(indx) & !indx),]
#   V1 V2  V3       V4 V5
# 1  1  4  10     ttts  3
# 2  2 10  22      ttt  2
# 4  4 10 584 0t000000  5
# 5  5 10 403     000s 15
# 7  7 10 123     000q 16

Explanation 说明

Using a more general example that includes numbers other 0 使用更通用的示例,其中包含除0以外的数字

v1 <- c("ttts", "ttt", "00000", "0t000000", "000s", "000", "000q", 
"000", "001")
indx <-suppressWarnings(as.numeric(v1)) #coerce non-numeric elements to NA
indx
#[1] NA NA  0 NA NA  0 NA  0  1

To exclude all 0 elements from the rest 从其余所有元素中排除所有0元素

indx1 <- !is.na(indx) & !indx #elements that are all 0's are TRUE
indx1
#[1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE  TRUE FALSE

Negate that 否定那个

!(indx1)
#[1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE  TRUE FALSE  TRUE

v1[!(indx1)]
#[1] "ttts"     "ttt"      "0t000000" "000s"     "000q"     "001"     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM