【问题标题】:Are integer vectors numeric vectors in R?R中的整数向量是数字向量吗?
【发布时间】:2014-09-25 22:49:31
【问题描述】:

我有一个整数向量,我希望我可以将其视为数字向量:

> class(pf$age)
[1] "integer"
> is.numeric(pf$age)
[1] TRUE

但是,当我尝试使用它来计算相关性时,出现错误:

> cor.test(x = "age", y = "friend_count", data = pf)
Error in cor.test.default(x = "age", y = "friend_count", data = pf) : 
  'x' must be a numeric vector

我对替代语法的最佳猜测也不起作用:http://pastie.org/9595290

发生了什么事?

编辑:

以下语法有效:

> x = pf$age
> y = pf$friend_count
> cor.test(x, y, data = pf, method="pearson", alternative="greater")

但是,我不明白为什么我不能在函数中指定 x 和 y(你可以使用其他 R 函数,如 ggplot)。 ggplotcor.test有什么区别?

【问题讨论】:

  • @Gregor,它没有。我将该示例包含在我的备用语法中。
  • 糟糕,我的错误是我在全局环境中定义了 agefriend_count,而我的 data 参数被忽略了。
  • @Gregor 别担心 :-)

标签: r vector


【解决方案1】:

您不能像在函数调用中那样使用字符串来引用变量。您想传递给 xy 参数数字向量。你传递了长度为 1 的字符向量:

> is.numeric("age")
[1] FALSE
> is.character("age")
[1] TRUE

因此您要求cor.test() 计算字符串"age""friend_count" 之间的相关性。

您还将cor.test()formula 方法与default 之一混淆了。您提供一个公式和一个data 对象您提供参数xy。你不能混搭。

两种解决方案是:

  1. with(pdf, cor.test(x = age, y = friend_count))
  2. cor.test( ~ age + friend_count, data = pf)

第一种使用默认方法,但我们允许自己直接使用with() 来引用pf 中的变量。第二种使用公式法。

关于你在标题中的问题;是的,整数向量在 R 中被视为数字:

> int <- c(1L, 2L)
> is.integer(int)
[1] TRUE
> is.numeric(int)
[1] TRUE

请注意下面评论中@Joshua Ulrich 的观点。正如 Joshua 所示,从技术上讲,整数与 R 中的数字略有不同。然而,这种差异在大多数情况下不需要关注用户,因为 R 可以根据需要转换/使用这些。这在某些地方确实很重要,例如.C() 电话。

【讨论】:

  • 我知道 Gavin 知道这一点,但作为对其他人的警告:我会小心地说“整数向量在 R 中被视为数字”。 is.numeric(integer())TRUE,但 identical(numeric(), integer())FALSE。这是因为 is.numeric 被记录为对于整数向量返回 TRUE
  • @JoshuaUlrich +1(我在掩饰这种微妙之处,因为我怀疑这不是 OP 的问题,但你澄清我的草率是对的 :-)
  • 感谢您澄清这一点
  • 这里有一个有点奇怪的错误,它利用整数不是数字的事实:stackoverflow.com/questions/25859502/…
【解决方案2】:

你可以使用'get'和字符串来获取数据:

age = pf$age
friend_count = pf$friend_count

或:

attach(pf)

那么以下应该可以工作:

cor.test(x = get("age"), y = get("friend_count"))

【讨论】:

    猜你喜欢
    • 2014-07-30
    • 2011-10-28
    • 2016-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    相关资源
    最近更新 更多