【问题标题】:Address columns in dataframe by numbers按数字寻址数据框中的列
【发布时间】:2020-03-15 20:14:58
【问题描述】:

有一个包含 3 列(y 和 2 个预测变量)的数据框。可以寻址列,例如与height$df1df1[,2]。结果相同。两者都是向量 (is.vector)。在某些情况下,结合confint 之类的公式,输出会有所不同。

此代码提供正确的结果:

confint(lm(df1[,1] ~ height, data=df1), "height")

这个不起作用,它以NA 值结束:

confint(lm(earning ~ df1[, 2], data=df1), "height")

希望使用列号来处理数据框,例如df1[, 2]。什么是正确的方法? 感谢任何帮助。

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以使用reformulate 来创建公式:

    confint(lm(reformulate(names(df1)[2], "earning"), df1), 'height')
    

    mtcars为例:

    confint(lm(reformulate(names(mtcars)[6], "mpg"), mtcars), 'wt')
    
    #       2.5 %    97.5 %
    #wt -6.486308 -4.202635
    

    【讨论】:

    • 以及如何使用更多变量来做到这一点,例如:mpg ~ wt + hp ?
    • @Eli3 confint(lm(reformulate(names(mtcars)[c(4, 6)], "mpg"), mtcars), 'wt') 像这样。
    【解决方案2】:

    一种选择是使用paste 创建一个公式,它应该可以工作

    confint(lm(paste0('earning ~ ', names(df1)[2]), data = df1), "height")
    

    使用一个可重现的小例子

    data(mtcars)
    fit <- lm(mpg ~ mtcars[,6], data = mtcars)
    confint(fit, 'wt')
    #   2.5 % 97.5 %
    #wt    NA     NA
    fit <- lm(paste0('mpg ~', names(mtcars)[6]), data = mtcars)
    confint(fit, 'wt')
    #       2.5 %    97.5 %
    #wt -6.486308 -4.202635
    

    【讨论】:

    • 它有效。以及如何使用mpg,resp。也赚钱?
    • 用数字寻址所有向量......在我的示例中也是“收入”。类似:confint(lm(names(df1)[1] ~ names(df1)[2], data = df1), "height") 谢谢。
    • @Eli3 随便confint(lm(paste0(names(df1)[1], " ~ ", names(df1)[2]), data = df1), "height")
    • #akrun:谢谢它有效。你能解释一下为什么它是这样工作的,而不是我的尝试 df1[, 2]?
    • @Eli3 在您的尝试中,以术语创建的属性是 df1[, 2] 而不是列名,因此它与列名不匹配
    猜你喜欢
    • 2013-04-20
    • 1970-01-01
    • 2018-09-21
    • 2017-05-09
    • 2012-09-06
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多