[英]Filtering R Rows based on data type
提示:本站为国内最大中英文翻译问答网站,提供中英文对照查看,鼠标放在中文字句上可显示英文原文。
我有一个带有以下列的 dataframe A
SN Sample1 Sample2
样本 1 和样本 2 要么有数值,要么有一些文本来表示不可能进行采样。
我需要保留at least one numeric value
任何行。
我的想法是过滤out rows based on having no numeric values
。
我通常使用这个: A[.is.na(as,numeric(A$sample1)), ]
但这只会查看其中一列。
我需要帮助才能在查看 Sample1 和 Sample2 的地方写出来。
基本上,我需要做的是
Sample 1 text Sample 2 text #then remove
Sample 1 numeric Sample 2 numeric #then keep
Sample 1 numeric Sample 2 text #then keep
Sample 1 text Sample 2 numeric #then keep
在 base R 中,您可以使用grepl
搜索数字,然后使用“或”运算符创建两个逻辑和索引, |
:
df[grepl("^-?\\d+\\.?\\d*$", df$a) | grepl("^-?\\d+\\.?\\d*$", df$b), ] #thanks @zephyryl
# a b
# 1 1 A
# 2 2 B
原始样本数据:
df <- data.frame(a = c(1, 2, "Abc"),
b = c(LETTERS[1:3]))
# a b
# 1 1 A
# 2 2 B
# 3 Abc C
您可以将现有代码变成 function(也抑制“强制警告引入的 NA”并处理原始向量中的NA
),然后使用apply()
按行应用:
is_coercible_numeric <- function(x) {
is.na(x) | !is.na(suppressWarnings(as.numeric(x)))
}
A[apply(dat, 1, \(col) any(is_coercible_numeric(col))), ]
# Sample1 Sample2
# 2 2 2
# 3 3 text3
# 4 text4 4
或者使用 dplyr:
library(dplyr)
A %>%
filter(if_any(Sample1:Sample2, is_coercible_numeric))
# Sample1 Sample2
# 1 2 2
# 2 3 text3
# 3 text4 4
示例数据:
A <- data.frame(
Sample1 = c("text1", 2, 3, "text4"),
Sample2 = c("text1", 2, "text3", 4)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.