且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-03 19:51:58

有多种方法可以执行此操作:

There are multiple ways you can do this :

转换为数字并删除 NA

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

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

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

Or with grepl find if there are any non-numeric characters in them and remove them

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))