令我惊讶的是,我以前没发现有人问过这个问题。
我的输入data.frame
a <- c(1,5.3,3,1,-8,6,-1)
b <- c(4,-2,1.0,"1 2","-","1.2.3","x")
df <- data.frame(a,b)
df
a b
1 1 4
2 5.3 -2
3 3 1
4 1 1 2
5 -8 -
6 6 1.2.3
7 -1 x期望输出
a b
1 1.0 4
2 5.3 -2
3 3.0 1我想出的
df[apply(df, 1, function(r) !any(is.na(as.numeric(r)))) ,]它起作用了,但它发出了一些丑陋的警告。
a b
1 1.0 4
2 5.3 -2
3 3.0 1
Warning messages:
1: In FUN(newX[, i], ...) : NAs introduced by coercion
2: In FUN(newX[, i], ...) : NAs introduced by coercion
3: In FUN(newX[, i], ...) : NAs introduced by coercion
4: In FUN(newX[, i], ...) : NAs introduced by coercion如果可能的话,有没有更好的使用R基的方法?
发布于 2021-11-23 01:54:14
一对使用基本R解决方案的strtoi (没有警告)
rowSums (全整数)
df[ !is.na( rowSums( sapply( df, strtoi ) ) ), ]
a b
1 1 4
2 5 -2
3 3 1complete.cases (全整数)
df[ complete.cases( sapply( df, strtoi ) ), ]
a b
1 1 4
2 5 -2
3 3 1更改后的编辑(一些浮动)
下一种方法是使用双sapply来触摸每个值,而不是向量。在有冲突模式的情况下,这是很重要的,也就是说,如果其他方式不能决定的话。
df
a b
1 1 4
2 5.3 -2
3 3 1
4 1 1 2
5 -8 -
6 6 1.3
7 -1 x
8 2.5 1.2.3
data.frame( na.omit( sapply( df, function(x)
sapply( x, function(y)
ifelse(grepl("^-?\\d+\\.\\d+$", y), as.numeric(y), strtoi(y)) ) )))
a b
1 1.0 4.0
5.3 5.3 -2.0
3 3.0 1.0
6 6.0 1.3发布于 2021-11-23 01:46:02
注意事项:修改问题后编辑
我不认为这些警告是个大问题。它们只是告诉您您已经知道的内容;当胁迫为数字时,4个字符值返回NA。
您可以将数据帧仅筛选为正数或负数值,然后使用dplyr将其转换为数字。
library(dplyr)
df %>%
filter(if_all(everything(), ~ grepl("^-?\\d+(\\.\\d+)?$", .x))) %>%
mutate(across(everything(), ~ as.numeric(.x)))结果:
a b
1 1.0 4
2 5.3 -2
3 3.0 1https://stackoverflow.com/questions/70074260
复制相似问题