![](/img/trans.png)
[英]How to find and delete a certain number of rows with the same consecutive value in a column in a dataframe in R?
[英]How to delete certain rows in R within dataframe
我的數據框是這樣的
class subject marks
1 bio 30
2 chem 40
3 bio 0
4 phy 60
5 maths 0
6 chem 0
我想從“標記”列中刪除所有具有“0”的行
我正在嘗試以下代碼,但它不起作用
df %>%
filter(!str_detect(marks, '0'))
我看到一條已刪除的評論,其中解釋了更多。 我會嘗試使它更具體。
您需要完全匹配,而不是使用str_detect
進行部分匹配: marks != 0
。 在您的情況下,部分匹配具有誤導性,因為 0 也出現在例如 60 中,實際上是所有marks
。 所以你不會擺脫任何行。 使用完全匹配: df %>% filter(marks != 0)
。
此外,對於像這樣的簡單任務,基本語法非常好,例如subset(df, marks != 0)
或df[df$marks != 0, ]
。
如果你想使用str_detect
,你應該像這樣使用模式^0
:
df <- read.table(text="class subject marks
1 bio 30
2 chem 40
3 bio 0
4 phy 60
5 maths 0
6 chem 0", header = TRUE)
library(dplyr)
library(stringr)
df %>%
filter(!str_detect(marks, "^0"))
#> class subject marks
#> 1 1 bio 30
#> 2 2 chem 40
#> 3 4 phy 60
由reprex 包於 2022-07-14 創建 (v2.0.1)
使用 base r 方法
a = read.table(text='class subject marks
1 bio 30
2 chem 40
3 bio 0
4 phy 60
5 maths 0
6 chem 0',header=T)
a=a[!a$marks==0,]
輸出:
> a
class subject marks
1 1 bio 30
2 2 chem 40
4 4 phy 60
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.