没有左引数的公式在R中表示什么,例如〜x? [英] What does a formula with no left argument mean in R, e.g. ~x?

查看:66
本文介绍了没有左引数的公式在R中表示什么,例如〜x?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在类似y ~ x的公式中,我将"y"视为"x"的函数.在数学中,这类似于f(x) = x.

I understand that in a formula like y ~ x I am looking at "y" as a function of "x". In maths this would be something like f(x) = x.

在R中,xtabs之类的函数可以不带左侧的方式使用公式对象,例如xtabs( ~ x).从我对公式的理解来看,我现在在数学= x中什么都没有作为"x"的函数看待,但是显然这不是R理解公式的方式(例如,它返回一个因素的列联表).

In R, functions like xtabs can take formula objects without a left side, e.g. xtabs( ~ x). From my understanding of formulas, I am now looking at nothing as a function of "x", in maths = x, but that is obviously not how R understands the formula (it returns a contingency table of a factor, for example).

那我怎么才能理解一个空的左手参数的含义呢?

So how can I understand the meaning of an empty left hand argument?

我确定这已经在某处得到了解释,但是我很难查询"R〜".

I'm sure this has been explained somewhere, but I have a hard time googling for "R ~".

推荐答案

公式仅在与它们一起使用的特定功能的上下文中才有意义.相同的公式可能意味着一个功能与另一个功能完全不同.

Formulas only have meaning in the context of the particular functions that work with them. The same formula may mean something completely different to one function vs. another function.

xtabs的情况下,它会将左手侧的总和与右​​手侧的总和相加,如果没有左手侧,则将计数.也就是说,默认的左手侧可以视为1的向量.例如这些都给出相同的结果

In the case of xtabs it sums the left hand side over the levels of the right hand side and if there is no left hand side it gives the counts. That is, the default left hand side can be regarded as a vector of ones. e.g. these each give the same result

x <- c(1, 1, 2, 2, 2)

# 1
xtabs(~ x)

# 2
ones <- rep(1, length = length(x))
xtabs(ones ~ x)

这也给出了类似的结果,但是在这种情况下,结果是数组而不是表:

This also gives a similar result but in this case the result is an array rather than a table:

# 3
tapply(ones, x, sum)

这篇关于没有左引数的公式在R中表示什么,例如〜x?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆