【问题标题】:Interpretation of negative index when subsetting a data.frame [duplicate]子集data.frame时负索引的解释[重复]
【发布时间】:2014-02-08 04:38:36
【问题描述】:

我对 R 非常陌生,有时会被代码卡住。我遇到了如下代码之一。下面代码中的-7是什么意思?

round(cor(longley[,-7]),3)

我明白: 四舍五入, longley 作为 data.frame, 3:四舍五入的数字,但不是-7。

【问题讨论】:

    标签: r indexing dataframe matrix-indexing


    【解决方案1】:

    命令longley[,-7] 表示:longley 中除第 7 列外的所有列。这称为负索引。

    查看?Extract 了解更多信息。

    【讨论】:

    • 非常感谢您的解释和参考非常有用的资源。
    【解决方案2】:

    在上下文[, -7] 中,这意味着从数据框longley 中删除7th 列(或从longley 中删除除7th 之外的所有列)。

    这是 R 101,您最好阅读一些介绍性材料。例如,这在 R 附带的 An Introduction to R 手册中很早就有介绍,或者可以从 R 网站访问。或者你可以阅读?Extract。

    这是一个例子

    > head(longley)
         GNP.deflator     GNP Unemployed Armed.Forces Population Year Employed
    1947         83.0 234.289      235.6        159.0    107.608 1947   60.323
    1948         88.5 259.426      232.5        145.6    108.632 1948   61.122
    1949         88.2 258.054      368.2        161.6    109.773 1949   60.171
    1950         89.5 284.599      335.1        165.0    110.929 1950   61.187
    1951         96.2 328.975      209.9        309.9    112.075 1951   63.221
    1952         98.1 346.999      193.2        359.4    113.270 1952   63.639
    > names(longley)
    [1] "GNP.deflator" "GNP"          "Unemployed"   "Armed.Forces" "Population"  
    [6] "Year"         "Employed"    
    > names(longley)[7]
    [1] "Employed"
    > head(longley[, -7])
         GNP.deflator     GNP Unemployed Armed.Forces Population Year
    1947         83.0 234.289      235.6        159.0    107.608 1947
    1948         88.5 259.426      232.5        145.6    108.632 1948
    1949         88.2 258.054      368.2        161.6    109.773 1949
    1950         89.5 284.599      335.1        165.0    110.929 1950
    1951         96.2 328.975      209.9        309.9    112.075 1951
    1952         98.1 346.999      193.2        359.4    113.270 1952
    

    【讨论】:

    • 非常感谢您的解释和参考非常有用的资源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    • 2015-03-28
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    相关资源
    最近更新 更多