error as.formula function: 尝试在NULL上设置属性

huangapple go评论59阅读模式
英文:

error as.formula function: attempt to set an attribute on NULL

问题

labels <- paste('label', seq(1, 8, 1), sep='', collapse = ' + ')

labels <- paste(labels, '+', 'label9')

labels <- as.formula(labels)

Error in class(ff) <- "formula" : attempt to set an attribute on NULL

What I need to get is label1 + label2 + label3 + label4 + label5 + label6 + label7 + label8 + label9 as a formula.

英文:

A quick question:

I'm building a NN model and I don't want to type in all the variables. Instead I'd like to save a variable with some of the col names and use it int he formula.

When I'm approaching it in this way, this code gives me an error.

Why and how can I fix it?

labels &lt;- paste(&#39;label&#39;,seq(1,8,1), sep=&#39;&#39;, collapse = &#39; + &#39;)

labels &lt;- paste(labels,&#39;+&#39;,&#39;label9&#39;)

labels &lt;- as.formula(labels)

Error in class(ff) &lt;- &quot;formula&quot; : attempt to set an attribute on NULL

What I need to get is label1 + label2 + label3 + label4 + label5 + label6 + label7 + label8 + label9 as a formula.

答案1

得分: 2

We may use paste with ~

as.formula(paste0(labels, "~ ."))
label1 + label2 + label3 + label4 + label5 + label6 + label7 + 
    label8 + label9 ~ .

Or with reformulate

reformulate(response = labels, ".")
label1 + label2 + label3 + label4 + label5 + label6 + label7 + 
    label8 + label9 ~ .
英文:

We may use paste with ~

as.formula(paste0(labels, &quot;~ .&quot;))
label1 + label2 + label3 + label4 + label5 + label6 + label7 + 
    label8 + label9 ~ .

Or with reformulate

 reformulate(response = labels, &quot;.&quot;)
label1 + label2 + label3 + label4 + label5 + label6 + label7 + 
    label8 + label9 ~ .

huangapple
  • 本文由 发表于 2023年2月6日 04:06:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定