在R中使用很长的字符串创建公式 [英] Creating formula using very long strings in R

查看:277
本文介绍了在R中使用很长的字符串创建公式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,我有一个非常大的数据帧的充满列名的向量.

I'm in a situation where I have a vector full of column names for a really large data frame.

让我们假设:x = c("Name", "address", "Gender", ......, "class" ) [大约100个变量]

Let's assume: x = c("Name", "address", "Gender", ......, "class" ) [approximatively 100 variables]

现在,我想创建一个公式,该公式将最终用于创建HoeffdingTree. 我正在使用以下公式创建公式:

Now, I would like to create a formula which I'll eventually use to create a HoeffdingTree. I'm creating formula using:

myformula <- as.formula(paste("class ~ ", paste(x, collapse= "+")))

这会引发以下错误:

解析错误(text = x)::1:360:意外的'else' 1:e +传播+祈祷forsonni +正义+想要+ amp + argue + blxcknicotine +心情+现在+正确+实际上+赫拉帕特拉+必须+简单+吸吮+那里+总是+ cookies +永远+一切+得到+不错+ nice + nigga +他们+时代+阿布+全部+阿利皮克

Error in parse(text = x) : :1:360: unexpected 'else' 1:e+spread+prayforsonni+just+want+amp+argue+blxcknicotine+mood+now+right+actually+herapatra+must+simply+suck+there+always+cookies+ever+everything+getting+nice+nigga+they+times+abu+all+alliepickl

以上语句中的paste部分工作正常,但将其作为as.formula的参数传递会引发各种奇怪的问题.

The paste part in the above statement works fine but passing it as an argument to as.formula is throwing all kinds of weird problems.

推荐答案

问题是您将R关键字用作列名. else是关键字,所以您不能将其用作常规名称.

The problem is that you have R keywords as column names. else is a keyword so you can't use it as a regular name.

一个简化的示例:

s <- c("x", "else", "z")
f <- paste("y~", paste(s, collapse="+"))
formula(f)
# Error in parse(text = x) : <text>:1:10: unexpected '+'
# 1: y~ x+else+
#              ^

解决方案是将您的单词包装在反引号`"中,以使R将其视为非语法变量名.

The solution is to wrap your words in backticks "`" so that R will treat them as non-syntactic variable names.

f <- paste("y~", paste(sprintf("`%s`", s), collapse="+"))
formula(f)
# y ~ x + `else` + z

这篇关于在R中使用很长的字符串创建公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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