[英]Removing rows which contain all 0's in r
我有一個這樣的文件。
"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
........................
我想的是,它包含所有的所有行0
在第四列中,如行3
和行6
與排沿8
被消除。 我如何在R中做到這一點? 謝謝!
使用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
編輯:根據評論者的建議,將grep
更改為grepl
。
我認為第8行也應該刪除。
我建議嘗試使用“ stringi”軟件包並執行以下操作:
library(stringi)
stri_count_fixed(mydf[, 4], "0") == nchar(mydf[, 4])
# [1] FALSE FALSE TRUE FALSE FALSE TRUE FALSE TRUE
您可以使用此邏輯向量從原始數據集中獲取子集。
在基數R中,您還可以嘗試:
vapply(strsplit(mydf[, 4], ""), function(x) all(x == "0"), logical(1L))
# [1] FALSE FALSE TRUE FALSE FALSE TRUE FALSE TRUE
另一種方法是:
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
使用更通用的示例,其中包含除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
從其余所有元素中排除所有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
否定那個
!(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.