gpt4 book ai didi

r - 使用 R 解释外部使用的符号公式

转载 作者:行者123 更新时间:2023-12-04 15:24:00 25 4
gpt4 key购买 nike

在 R 中,公式对象是象征性的,似乎很难解析。但是,我需要将这样的公式解析为一组显式的标签,以便在 R 之外使用。

(1)

出租 f代表model formulae其中未指定响应,例如~V1 + V2 + V3 ,我尝试过的一件事是:

t <- terms(f)
attr(t, "term.labels")

但是,如果 f 中的某些变量,这并没有得到确切的信息。是绝对的。例如,让 V1是一个有 2 个类别的分类变量,即一个 bool 值,并让 V2成为双人。

因此,由 ~V1:V2 指定的模型应该有 2 个参数:“intercept”和“xyes:z”。同时,由 ~V1:V2 - 1 指定的模型应该有参数“xno:z”和“xyes:z”。但是,没有办法告诉函数 terms()哪些变量是分类的(以及有多少个类别)无法解释这些。相反,它只有 V1:V2在它的“terms.labels”中,这在 V1 的上下文中没有任何意义。是绝对的。

(2)

另一方面,使用 model.matrix是获得我想要的东西的简单方法。问题是它需要一个 data论点,这对我不利,因为我只想明确解释在 R 之外使用的符号公式。这种获取方法会浪费很多时间(相对而言),因为 R 必须从外部源读取数据它真的需要知道公式是哪些变量是分类变量(以及多少个类别)以及哪些变量是 double 变量。

有什么方法可以使用 'model.matrix' 只指定数据类型,而不是实际数据?如果没有,还有什么可行的解决方案?

最佳答案

好吧,只有在拥有数据的情况下才能确定给定的变量是因子还是数值。所以你不能没有数据参数。但是您需要的只是结构,而不是数据本身,因此您可以使用包含所有正确类型的列的 0 行数据框。

f <- ~ V1:V2
V1numeric <- data.frame(V1=numeric(0), V2=numeric(0))
V1factor <- data.frame(V1=factor(c(), levels=c("no","yes")), V2=numeric(0))

查看两个data.frames:
> V1numeric
[1] V1 V2
<0 rows> (or 0-length row.names)
> str(V1numeric)
'data.frame': 0 obs. of 2 variables:
$ V1: num
$ V2: num
> V1factor
[1] V1 V2
<0 rows> (or 0-length row.names)
> str(V1factor)
'data.frame': 0 obs. of 2 variables:
$ V1: Factor w/ 2 levels "no","yes":
$ V2: num

使用 model.matrix用这些
> model.matrix(f, data=V1numeric)
(Intercept) V1:V2
attr(,"assign")
[1] 0 1
> model.matrix(f, data=V1factor)
(Intercept) V1no:V2 V1yes:V2
attr(,"assign")
[1] 0 1 1
attr(,"contrasts")
attr(,"contrasts")$V1
[1] "contr.treatment"

如果你有一个真实的数据集,很容易从保留列信息的数据中得到一个 0 行的 data.frame。只需用 FALSE 下标即可.如果您拥有具有正确属性的 data.frame,则无需手动构建 data.frame。
> str(mtcars)
'data.frame': 32 obs. of 11 variables:
$ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
$ cyl : num 6 6 4 6 8 6 8 4 4 6 ...
$ disp: num 160 160 108 258 360 ...
$ hp : num 110 110 93 110 175 105 245 62 95 123 ...
$ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
$ wt : num 2.62 2.88 2.32 3.21 3.44 ...
$ qsec: num 16.5 17 18.6 19.4 17 ...
$ vs : num 0 0 1 1 0 1 0 1 1 1 ...
$ am : num 1 1 1 0 0 0 0 0 0 0 ...
$ gear: num 4 4 4 3 3 3 3 4 4 4 ...
$ carb: num 4 4 1 1 2 1 4 2 2 4 ...
> str(mtcars[FALSE,])
'data.frame': 0 obs. of 11 variables:
$ mpg : num
$ cyl : num
$ disp: num
$ hp : num
$ drat: num
$ wt : num
$ qsec: num
$ vs : num
$ am : num
$ gear: num
$ carb: num

关于r - 使用 R 解释外部使用的符号公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16592990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com