首页 文章

r中的R:公式中的变量

提问于
浏览
0

我在文本数据上使用决策树,并且我将n个最常用的术语存储在变量中,并尝试在 rpart 函数的公式中使用此变量 . 但是,我得到的错误如下:

Error in model.frame.default(formula = class ~ x, data = dtm.df, na.action = function (x): variable lengths differ (found for 'x')

x = findFreqTerms(dtm, 0.5)
fit = rpart(class ~ x, data = dtm.train

是否可以自动填写公式而无需手动输入每个功能?

1 回答

  • 0

    Technical basis for the solution

    您希望实现的目标背后的想法是从最常用的术语(字符串)创建公式 .

    广泛的想法是从变量创建公式,而不是像我的评论中那样使用输入文本(即直接写 class~Variable1 + Variable2 + Variable3 ) .

    This link provide an example on how to use a string to create a formula,您还需要查看 paste() function in R documentationcollapse 参数 .

    Code

    # First find your most frequent terms
    x <- findFreqTerms(dtm, 0.5)
    
    # Then prepare the variables for the formula
    sMeasureVar <- "class"
    sGroupVars  <- paste(x, collapse = " + ")
    
    # Create the formula from the variables
    fRpart <- as.formula(paste(sMeasureVar, sGroupVars, sep=" ~ "))
    
    # Fit the tree associated
    fit <- rpart(formula = fRpart , data = dtm.train)
    

相关问题