【问题标题】:'x' must be a numeric vector: Error from data.frame of numbers'x' 必须是数字向量:来自数据的错误。数字帧
【发布时间】:2011-11-30 22:02:31
【问题描述】:

我正在对文件/表中的两列运行 cor.test。

tmp <- read.table(files_to_test[i], header=TRUE, sep="\t")
## Obtain Columns To Compare ##
colA <-tmp[compareA]
colB <-tmp[compareB]
# sctr = 'spearman cor.test result'
sctr <- cor.test(colA, colB, alternative="two.sided", method="spearman")

但我遇到了这个令人困惑的错误......

Error in cor.test.default(colA, colB, alternative = "two.sided", method = "spearman") : 
'x' must be a numeric vector

列中的值是数字,但是

is.numeric(colA) = FALSE 
class (colA) = data.frame

我错过了什么?

【问题讨论】:

  • str(colA)str(colB) 的结果是什么。我猜数据是作为因子或字符数据读入的,可能是因为您正在读取的数据中存在错误字符。
  • @Chase:我赞成您的评论,但后来意识到这不是问题(请参阅下面的两个答案)。事后看来,我认为这有点误导,但我无法删除我的赞成票......
  • @Ben 和@Chase:给str 结果的建议是好的。 (我投了第二个赞成票)。

标签: r dataframe


【解决方案1】:

在您的选择器前加一个逗号。当您在具有单个索引变量且不带逗号的 data.frame 对象中进行选择时,它会将一列提取为列表元素保留类型。因此,它仍然是一个data.frame。但是,data.frame 对象允许您使用矩阵样式表示法进行选择,然后您将获得一个简单的向量。所以就改变

colA <-tmp[compareA]
colB <-tmp[compareB]

colA <-tmp[,compareA]
colB <-tmp[,compareB]

我认为这更符合 data.frame 类型的精神,而不是双括号 ([[) 选择器,它会做一些类似的事情,但符合底层列表类型的精神。它们也与单个项目和行选择器无关。因此,在使用 data.frame 做多种事情的代码中,双括号选择器有点像一只奇怪的鸭子。

【讨论】:

  • 这和我上面的解决方案一样有效。我想知道是否存在它们行为不同的极端情况......
【解决方案2】:

尝试使用tmp[[compareA]]tmp[[compareB]] 而不是单括号。您想提取数字向量,而您所做的是提取单列数据帧。比较以下:

> z <- data.frame(a=1:5,b=1:5)
> str(z["a"])
'data.frame':   5 obs. of  1 variable:
 $ a: int  1 2 3 4 5
> is.numeric(z["a"])
[1] FALSE
> str(z[["a"]])
 int [1:5] 1 2 3 4 5
> is.numeric(z[["a"]])
[1] TRUE

cor.test试试这些:

单括号:错误如上。

> cor.test(z["a"],z["b"])
Error in cor.test.default(z["a"], z["b"]) : 'x' must be a numeric vector

双括号:有效。

> cor.test(z[["a"]],z[["b"]])

    Pearson's product-moment correlation

data:  z[["a"]] and z[["b"]] 
[snip snip snip]

正如@Aaron 在下面指出的那样,cor 将通过将单列数据帧转换为矩阵来很好地处理它们——但cor.test 不会。 (这可以在 r-devel@r-project.org 上提出,或者 ?? 作为愿望清单项目提交给 R 错误跟踪器...)

另请参阅:Numeric Column in data.frame returning "num" with str() but not is.numeric()What's the biggest R-gotcha you've run across?(可能还有其他)

【讨论】:

  • 虽然这确实使代码更清晰,但cor 会将数据帧转换为矩阵,因此这应该与 OP 的代码具有相同的结果。
  • 我没有仔细阅读; OP 正在使用cor.test,它不进行此转换。我怀疑你是对的。
猜你喜欢
  • 1970-01-01
  • 2018-12-04
  • 2014-07-27
  • 1970-01-01
  • 2023-03-28
  • 2015-12-13
  • 2023-04-07
  • 1970-01-01
  • 2022-01-05
相关资源
最近更新 更多