我试图将具有非数字值的所有单元格转换为缺失数据(NA)。我尝试了类似的将特定值转换为缺失数据的方法,例如:
recode_missing <- function (g, misval)
{
a <- g == misval
temp = g
temp [a] <- NA
return (temp)
}
这很有效:优雅的R解决方案。
我试图解码像a <- g == is.numeric ()
(语法错误),a <- is.numeric (g): (Error: (list) object cannot be coerced to type 'double'), or even
a [,]
remove_nn <- function (data)
{
# removes all non-numeric columns
numeric_columns <- sapply (data, is.numeric)
return (data [, numeric_columns])
} ### remove_nn ###
但是这会删除列并将数据帧转换为某个矩阵。
有人可以建议如何将单个非数字单元格转换为NA,同时保持数据结构完好无损?
编辑
正如评论所指出的那样,在数值海洋中没有单独的字符串值。只是数字或其他的向量。我现在想知道是什么导致了medians <- apply (data, 2, median)
中的非数字错误。我有很多载体,通过眼睛检查证明没用。我发布了num <- sapply (data, is.numeric)
和下一个data [,!num]
。这给了我非数字的列。在一种情况下,由一个单元格值包含多余的“。文件由电子表格预处理,如果只有一个单元格是非数字的,则完整的向量被视为非数字。
根据您的编辑,您有向量应该是数字,但由于在读入过程中引入了一些错误数据,数据已转换为另一种格式(可能是character
或factor
)。
这是一个例子。 mydf1 <- mydf2 <- mydf3 <-
data.frame(...)
只用相同的数据创建了三个data.frame
s。
# I'm going to show three approaches
mydf1 <- mydf2 <- mydf3 <- data.frame(
A = c(1, 2, "x", 4),
B = c("y", 3, 4, "-")
)
str(mydf1)
# 'data.frame': 4 obs. of 2 variables:
# $ A: Factor w/ 4 levels "1","2","4","x": 1 2 4 3
# $ B: Factor w/ 4 levels "-","3","4","y": 4 2 3 1
一种方法是让R将任何无法转换为数字的值强制转换为NA
:
## You WILL get warnings
mydf1[] <- lapply(mydf1, function(x) as.numeric(as.character(x)))
# Warning messages:
# 1: In FUN(X[[i]], ...) : NAs introduced by coercion
# 2: In FUN(X[[i]], ...) : NAs introduced by coercion
str(mydf1)
# 'data.frame': 4 obs. of 2 variables:
# $ A: num 1 2 NA 4
# $ B: num NA 3 4 NA
另一种选择是使用makemeNA
的my SOfun package:
library(SOfun)
makemeNA(mydf2, "[^0-9]", FALSE)
# A B
# 1 1 NA
# 2 2 3
# 3 NA 4
# 4 4 NA
str(.Last.value)
# 'data.frame': 4 obs. of 2 variables:
# $ A: int 1 2 NA 4
# $ B: int NA 3 4 NA
这个函数有点不同,因为它使用type.convert
进行转换,并且可以处理更多特定的规则以转换为NA
(就像你可以在将数据读入R时使用na.strings
的向量)。
关于你的错误,我相信你会在你的as.numeric
上尝试data.frame
来获得你所显示的错误。
例:
# Your error...
as.numeric(mydf3)
# Error: (list) object cannot be coerced to type 'double'
你不会在matrix
上得到那个错误(但你仍会得到警告)....
# You'll get a warning
as.numeric(as.matrix(mydf3))
# [1] 1 2 NA 4 NA 3 4 NA
# Warning message:
# NAs introduced by coercion
为什么我们不需要明确使用as.character
? as.matrix
为您做到这一点:
str(as.matrix(mydf3))
# chr [1:4, 1:2] "1" "2" "x" "4" "y" "3" "4" "-"
# - attr(*, "dimnames")=List of 2
# ..$ : NULL
# ..$ : chr [1:2] "A" "B"
你怎么能用这些信息?
mydf3[] <- as.numeric(as.matrix(mydf3))
# Warning message:
# NAs introduced by coercion
str(mydf3)
# 'data.frame': 4 obs. of 2 variables:
# $ A: num 1 2 NA 4
# $ B: num NA 3 4 NA
简单是最好的。选择列 - 我选择了第4列到第31列。
df[,4:31] <- as.numeric(as.factor(as.character(df[,4:31])))