繁体   English   中英

从包含特定列中的字符串的数据框中删除行

[英]Removing rows from dataframe that contains string in a particular column

所以我在 R 中清理一个巨大的数据文件,一个例子如下所示:

ID       Score
1001       4
1002       2
1003       h
1004       v
1005       3

因为 Score 列的类是“字符”,所以我想使用 as.numeric 函数将 4,20 和 30 转换为数值。 但是由于数据是脏的(包含不合理的字符串,如 h、v),我收到消息:

NAs introduced by coercion.

当我运行以下命令时:

as.numeric(df$Score)

所以我现在想要做的是删除包含带字母的字符串的数据框中的行,以便我获得:

ID       Score
1001       4
1002       2
1005       3

有多种方法可以做到这一点:

转换为数字并删除NA

subset(df, !is.na(as.numeric(Score)))

#    ID Score
#1 1001     4
#2 1002    20
#5 1005    30

或者使用grepl查找其中是否有任何非数字字符并将其删除

subset(df, !grepl('\\D', Score))

这也可以用grep来完成。

df[grep('\\D', df$Score, invert = TRUE), ]

数据

df <- structure(list(ID = 1001:1005, Score = c("4", "20", "h", "v", 
"30")), class = "data.frame", row.names = c(NA, -5L))

您可以使用str_detecttidyverse包,如下所示:

df[str_detect(df$Score, "\\d"),]

或者

df %>% filter(str_detect(df$Score, "\\d"))

两者都产生输出:

#    ID Score
#1 1001     4
#2 1002    20
#5 1005    30

希望能帮助到你。

暂无
暂无

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

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