0

我有这个矩阵:

Catergory  Reason          Species
[1,] "Decline"  "Genuine"       "24"   
[2,] "Improved" "Genuine"       "16"    
[3,] "Improved" "Misclassified" "24"   
[4,] "Decline"  "Misclassified" "16"   
[5,] "Decline"  "taxonomic"     "24"   
[6,] "Improved" "Taxonomic"     "16"   
[7,] "Decline"  "Unclear"       "24"   
[8,] "Improved" "Unclear"       "16"   

我想将第三列设为数字,所以我尝试:

Reasonstats[,3]<-as.numeric(Reasonstats[,3])

它没有给我任何错误,但值仍然不是数字。如果我只是这样做

as.numeric(Reasonstats[,3])

它给了我一个数字列表,如果我这样做了

Reasonstats[,3]<-2

它在2罚款。

谁能告诉我哪里出错了?

谢谢

4

1 回答 1

1

要了解“出了什么问题”,您需要从阅读 的帮助页面开始?matrix,这将引导您进入 的帮助页面?as.vector。阅读?as.vector,你会发现:

as.vector,一个泛型,试图将其参数强制转换为模式向量mode(默认是强制转换为最方便的向量模式)

举几个例子来理解这一点:

A <- c(TRUE, TRUE, FALSE)
A
# [1]  TRUE  TRUE FALSE
mode(A)
# [1] "logical"
B <- c(TRUE, TRUE, 0)
B
# [1] 1 1 0
as.logical(B)
# [1]  TRUE  TRUE FALSE
mode(B)
# [1] "numeric"
C <- c(TRUE, FALSE, "zero")
C
# [1] "TRUE"  "FALSE" "zero" 
mode(C)
# [1] "character"

因此,理解as.vector不能包含混合原子模式,我们可以得出结论,a matrix(基本上是vector具有dim指定行数和列数的属性)也不能包含混合原子模式。

阅读更多 R 中的存储结构,您会遇到data.frame. 的帮助页面将?data.frame其描述为:

... 一种类似矩阵的结构,其列可能具有不同的类型(数字、逻辑、因子和字符等)。

因此,如果您想要一个如图所示的矩形表格,但具有不同类型的列,您应该使用 a data.frame,而不是 a matrix

假设你matrix是“m”,定义为:

m <- structure(
  c("Decline", "Improved", "Improved", "Decline", "Decline", 
    "Improved", "Decline", "Improved", "Genuine", "Genuine", 
    "Misclassified", "Misclassified", "taxonomic", "Taxonomic",
    "Unclear", "Unclear", "24", "16", "24", "16", "24", "16", 
    "24", "16"), 
  .Dim = c(8L, 3L), 
  .Dimnames = list(NULL, c("Catergory", "Reason", "Species")))

首先,将其转换为data.frame

m2 <- data.frame(m, stringsAsFactors=FALSE)

然后将您的“物种”列转换为数字:

m2$Species <- as.numeric(m2$Species)

这是结果及其结构。

m2
#   Catergory        Reason Species
# 1   Decline       Genuine      24
# 2  Improved       Genuine      16
# 3  Improved Misclassified      24
# 4   Decline Misclassified      16
# 5   Decline     taxonomic      24
# 6  Improved     Taxonomic      16
# 7   Decline       Unclear      24
# 8  Improved       Unclear      16
str(m2)
# 'data.frame':  8 obs. of  3 variables:
#  $ Catergory: chr  "Decline" "Improved" "Improved" "Decline" ...
#  $ Reason   : chr  "Genuine" "Genuine" "Misclassified" "Misclassified" ...
#  $ Species  : num  24 16 24 16 24 16 24 16
于 2013-07-18T17:29:02.500 回答