在R中删除整个原子矢量的行/列

时间:2013-05-26 19:33:58

标签: r vector statistics

如何在 R 中删除原子矢量的整列/行?

我在Q& A网站上发现的所有内容都无效......

每次我收到不同的错误:

  1. := is not an operator
  2. $ not working on atomic vectors
  3. number of items to replace is not a multiple of replacement length
  4. 这是我的数据

    > print(nominalTable)
    
                MORTGAGE NONE OTHER OWN RENT
      36 months      854    1     4 165  928
      60 months      294    0     1  35  218
    

    我想删除NONEOTHER列,以便mosaicplot忽略它们。

    更新

    > dput(nominalTable)
    structure(c(854L, 294L, 1L, 0L, 4L, 1L, 165L, 35L, 928L, 218L
    ), .Dim = c(2L, 5L), .Dimnames = structure(list(c("36 months", 
    "60 months"), c("MORTGAGE", "NONE", "OTHER", "OWN", "RENT")), .Names = c("", 
    "")), class = "table")
    

3 个答案:

答案 0 :(得分:4)

您可以指定要保留的列的名称,例如:

> nominalTable[, c('MORTGAGE', 'OWN', 'RENT')]

            MORTGAGE OWN RENT
  36 months      854 165  928
  60 months      294  35  218

或者按其ID删除不需要的列:

> nominalTable[, -(2:3)]

            MORTGAGE OWN RENT
  36 months      854 165  928
  60 months      294  35  218

有关详细信息,请参阅?'['

答案 1 :(得分:1)

您也可以为变量

指定NULL值
Mort <- read.table(
  header=TRUE, text='
MORTGAGE NONE OTHER OWN RENT
36_months      854    1     4 165  928
60_months      294    0     1  35  218')
names(Mort) # 5 variables
# [1] "MORTGAGE" "NONE"     "OTHER"    "OWN"      "RENT"
Mort$NONE <- Mort$OTHER <- NULL # set both to NULL
names(Mort) # 3 variables now
#[1] "MORTGAGE" "OWN"      "RENT" 

答案 2 :(得分:0)

这也有效:

subset.matrix(nominalTable,select=-c(NONE,OTHER))

(如果只是普通subset工作会很好,但它并不能很好地理解表格)