繁体   English   中英

R中的整数向量是数字向量吗?

[英]Are integer vectors numeric vectors in R?

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

> 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(就像使用ggplot类的其他R函数一样)。 ggplotcor.test什么cor.test

您不会像在函数调用中那样使用字符串来引用变量。 您想传递给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()调用。

您可以对字符串使用'get'来获取数据:

age = pf$age
friend_count = pf$friend_count

要么:

attach(pf)

那么以下应该工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM