【问题标题】:How can I select columns/rows with the opposite of the column/row names in R? [duplicate]如何选择与 R 中的列/行名称相反的列/行? [复制]
【发布时间】:2017-08-11 08:25:24
【问题描述】:

我有一个带有特定列名的矩阵或数据框。使用包含一些列名的向量,我可以轻松地处理矩阵的这些列。但是还有一种简单的方法来解决向量中未列出的相反列:

mat <- matrix(c(1:12), ncol=4)
colnames(mat) <- c("a", "b", "c", "d")
not_target_col <- c("a", "b")

在这种情况下,我喜欢列 cd。 我搜索这样的东西,没有做额外的步骤:

pos <- colnames(mat) != not_target_col
mat[,pos]

补充说明

我想更清楚一点:当我有一个数字向量时,当我添加 *-1 时,我可以得到相反的结果

not_target_col <- c(1,2)
mat[,not_target_col * -1]

当我使用逻辑向量时,也有类似的技术。这里我只需要添加一个!

not_target_col <- c(T,T,F,F)
mat[,!not_target_col]

【问题讨论】:

  • @akrun,我现在要做什么?
  • 你无能为力。有人会欺骗它标记它
  • 我在下面添加了另一个解决方案

标签: r


【解决方案1】:

另一个选项是%in%

mat[, !colnames(mat) %in% not_target_col]
#     c  d
#[1,] 7 10
#[2,] 8 11
#[3,] 9 12

【讨论】:

    【解决方案2】:

    我们可以在列名(colnames)和not_target_col之间使用setdiff来获取与not_target_col不匹配的列名。

    setdiff(colnames(mat), not_target_col)
    #[1] "c" "d"
    

    如果我们需要从矩阵中选择那些列

    mat[, setdiff(colnames(mat), not_target_col)]
    
    #     c  d
    #[1,] 7 10
    #[2,] 8 11
    #[3,] 9 12
    

    【讨论】:

      猜你喜欢
      • 2021-07-21
      • 1970-01-01
      • 1970-01-01
      • 2020-06-09
      • 2014-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多