【问题标题】:Discriminant analysis and column name in the code代码中的判别分析和列名
【发布时间】:2015-03-07 02:18:09
【问题描述】:

我一直在编写代码来简化使用 lda 函数执行判别分析的过程。但实际上我有一个我无法解决的步骤。也是我必须在代码中引入分类列的名称的时候。假设我们有下一张表(称为smoke),其中Factor 列代表组(在我们的例子中是smoker 和nsmok)。

 smoke

     Factor  Lung  Heart    Blood
  1   smoker  7       22     15
  2   smoker  8       21     12
  3   nsmok   22       9      5

这是我一直在准备的代码。请查看代码中的 XXXX(出现两次)。我希望他们自动写分类列的名称,而不是直接写两次。

lda=lda(XXXX~.,data=Smoke)
plot(lda)
lda 
lda$counts
lda$svd
lda.p=predict(lda) 
Tabla=table(Smoke$XXXX,lda.p$class)
Tabla
diag(prop.table(Tabla, 1))
sum(diag(prop.table(Tabla)))

我以为写...

colnames(Table)[1]

... 会解决的。但实际上在运行代码时仍然存在一些错误。 否则,我虽然这样直接介绍名字:

Column_Factor-> Factor

在代码的两个地方写上 Column_Factor 就可以解决这个问题。但事实并非如此。

有什么想法吗?

【问题讨论】:

    标签: r


    【解决方案1】:

    你可以这样做:

    library(MASS)
    
    #gets the column name of the factor, maybe check if there is only one factor column first
    Column_Factor <- names(Smoke)[sapply(Smoke, class)=="factor"]
    
    #creates the formula by pasting the name and the RHS
    lda <- lda(as.formula(paste(Column_Factor,"~.",sep="")),data=Smoke)
    
    plot(lda)
    lda 
    lda$counts
    lda$svd
    lda.p=predict(lda) 
    
    #selects the column using the variable
    Tabla=table(Smoke[,Column_Factor],lda.p$class)
    Tabla
    diag(prop.table(Tabla, 1))
    sum(diag(prop.table(Tabla)))
    

    【讨论】:

    • 完美的好。我知道了!但是,我必须更正代码中的一个错误:第一个 Column_factor 必须是两个大写字母 (Column_Factor) 的单词。你能纠正一下吗?
    猜你喜欢
    • 2015-01-01
    • 1970-01-01
    • 2015-01-15
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 2013-12-10
    • 2018-07-08
    相关资源
    最近更新 更多