[英]Are integer vectors numeric vectors in R?
I have an integer vector that I expected I could treat as a numeric vector: 我有一个整数矢量,我希望可以将其视为数字矢量:
> class(pf$age)
[1] "integer"
> is.numeric(pf$age)
[1] TRUE
However, when I try to use it to calculate a correlation, I get an error: 但是,当我尝试使用它来计算相关性时,出现错误:
> 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
None of my best guesses at alternate syntax work either: http://pastie.org/9595290 我对备用语法的最佳猜测也都不是: http : //pastie.org/9595290
What's going on? 这是怎么回事?
Edit: 编辑:
The following syntax works: 以下语法有效:
> x = pf$age
> y = pf$friend_count
> cor.test(x, y, data = pf, method="pearson", alternative="greater")
However, I don't understand why I can't specify x and y in the function (as you can with other R functions like ggplot
). 但是,我不明白为什么不能在函数中指定x和y(就像使用
ggplot
类的其他R函数一样)。 What is the difference between ggplot
and cor.test
? ggplot
和cor.test
什么cor.test
?
You don't refer to variables using character strings like that in a function call. 您不会像在函数调用中那样使用字符串来引用变量。 You want to pass to the
x
and y
arguments numeric vectors. 您想传递给
x
和y
参数数字矢量。 You passed length 1 character vectors: 您传递了长度为1的字符向量:
> is.numeric("age")
[1] FALSE
> is.character("age")
[1] TRUE
Hence you were asking cor.test()
to compute the correlation between the strings "age"
and "friend_count"
. 因此,您要求
cor.test()
计算字符串"age"
和"friend_count"
之间的相关性。
You also mixed up the formula
method of cor.test()
with the default
one. 您还将
cor.test()
的formula
方法与default
方法混合在一起。 You supply a formula and a data
object or you supply arguments x
and y
. 您提供公式和
data
对象, 或者提供参数x
和y
。 You can't mix and match. 您不能混搭。
Two solutions are: 两种解决方案是:
with(pdf, cor.test(x = age, y = friend_count))
cor.test( ~ age + friend_count, data = pf)
The first uses the default method, but we allow ourselves to refer to the variables in pf
directly by using with()
. 第一种使用默认方法,但是我们允许自己使用
with()
直接引用pf
的变量。 The second uses the formula method. 第二种使用公式方法。
As to your question in the title; 关于标题中的问题; yes, integer vectors are considered numeric in R:
是的,R中将整数向量视为数字:
> int <- c(1L, 2L)
> is.integer(int)
[1] TRUE
> is.numeric(int)
[1] TRUE
Do note @Joshua Ulrich's point in the comment below . 请在下面的评论中注意@Joshua Ulrich的观点 。 Technically integers are slightly different to numerics in R as Joshua shows.
如Joshua所示,从技术上讲,整数与R中的数字略有不同。 However this difference need not concern users most of the time as R can convert/use these as needed.
但是,由于R可以根据需要转换/使用这些内容,因此这种差异在大多数情况下都不必关心用户。 It does matter in some places, such as
.C()
calls for example. 在某些地方确实很重要,例如
.C()
调用。
You can use 'get' with strings to get data: 您可以对字符串使用'get'来获取数据:
age = pf$age
friend_count = pf$friend_count
or: 要么:
attach(pf)
then following should work: 那么以下应该工作:
cor.test(x = get("age"), y = get("friend_count"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.