【问题标题】:Subsetting an array based on multiple columns基于多列对数组进行子集化
【发布时间】:2014-11-20 17:14:54
【问题描述】:

我在 r 中有一个大数组,并希望使用从不同矩阵获得的点对其进行子集化。

,,1 
34  1  1  3  4
32  1  3  4  5
23  1  1  3  4
35  1  3  4  4
23  1  2  3  4

,,2 
234  1  1  3  4
32   1  3  4  5
324  1  1  3  4
23   1  3  4  4
232  1  2  3  4 

并希望它返回

34  1  1  3  4
23  1  1  3  4
23  1  2  3  4
234  1  1  3  4
324  1  1  3  4
232  1  2  3  4 

以某种格式。

这些特定的行将在我根据最后 3 列选择时返回 (即我想要最后 3 位数字 1,3,4 和 2,3,4 的所有行)

【问题讨论】:

    标签: arrays r subset


    【解决方案1】:

    一种方法是

    m1 <- apply(ar1, 2, `[`)
    m1[m1[,2]%in% 1:2 & m1[,3]==3 & m1[,4]==4,]
     #      [,1] [,2] [,3] [,4]
    #[1,]    1    1    3    4
    #[2,]    1    1    3    4
    #[3,]    1    2    3    4
    #[4,]    1    1    3    4
    #[5,]    1    1    3    4
    #[6,]    1    2    3    4
    

    或者

     res <- do.call(rbind,lapply(seq(dim(ar1)[3]), function(i) {
                          x1 <- ar1[,,i]
                          x2 <- t(x1[,-1])
                         x1[colSums(x2==c(1,3,4)|x2==c(2,3,4))==3,]}))
    
    res
    
    #     [,1] [,2] [,3] [,4]
    #[1,]    1    1    3    4
    #[2,]    1    1    3    4
    #[3,]    1    2    3    4
    #[4,]    1    1    3    4
    #[5,]    1    1    3    4
    #[6,]    1    2    3    4
    

    更新

    假设valuesmatch 是否在matrix 中,每一行作为匹配向量。

     toMatch <- rbind(c(1,3,4), c(2,3,4), c(4,3,2), c(1,9,4))
     indx1 <- apply(toMatch, 1, paste, collapse="")
    
     res <- do.call(rbind,lapply(seq(dim(ar1)[3]), function(i) {
                           x1 <- ar1[,,i]
                           x1[apply(x1[,-1], 1, paste, collapse='') %in% indx1,]
                                     }))
    

    数据

    ar1 <- structure(c(1, 1, 1, 1, 1, 1, 3, 1, 3, 2, 3, 4, 3, 4, 3, 4, 5, 
    4, 4, 4, 1, 1, 1, 1, 1, 1, 3, 1, 3, 2, 3, 4, 3, 4, 3, 4, 5, 4, 
    4, 4), .Dim = c(5L, 4L, 2L))
    

    【讨论】:

    • 如果我想添加多组我希望保留的坐标,是否有一种更简单的方法来输入它们,而不是使用方法 2 输入每个三重奏。
    • @T_stats_3 你在矩阵或列表中有这些坐标集吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多