如何找到等于给定列的所有列?

时间:2019-01-21 15:00:59

标签: r

给定一个矩阵和一个特定的列索引,我如何才能找到等于该列的所有列(或最多等于该列的t个列向量)。

例如:

m=matrix(data=c(2,2,2,2,3,0,2,2), ncol = 4)

相等的列为1 & 2 & 4

如果列index=1可以检索2 & 4

如果t=1我将仅获得第二列24-th列。

2 个答案:

答案 0 :(得分:0)

我假设您在创建示例矩阵方面有错字。这是获取所需索引的直接方法。

m=matrix(data=c(2,2,2,2,3,0,2,2), ncol=4)

equal_cols = function(m, col_index){
    out = NULL
    for (i in (1:NCOL(m))[-col_index]){
        if (all(m[,col_index] == m[,i]))
            out = c(out, i)
        }
    return (out)
    }

equal_cols(m, 1)
# 2 4

答案 1 :(得分:0)

鉴于ncol = 4,您可以使用apply和哪个函数:

@Value("classpath:test.graphqls")
private Resource schemaResource;
private GraphQL graphQL;

@PostConstruct
private void loadSchema() throws IOException {
        File schemaFile = schemaResource.getFile();
        TypeDefinitionRegistry registry = new SchemaParser().parse(schemaFile);
        RuntimeWiring wiring = buildWiring();
        GraphQLSchema schema = new SchemaGenerator().makeExecutableSchema(registry, wiring);
        graphQL = GraphQL.newGraphQL(schema).build();
}


private RuntimeWiring buildWiring() {
        initializeFetchers();
        return RuntimeWiring.newRuntimeWiring()
                .type("Query", typeWriting -> typeWriting
                        .dataFetcher("getItem", dictionaryItemFetcher)

                )
                .build();
}

private void initializeFetchers() {
        dictionaryItemFetcher = dataFetchingEnvironment ->
                dictionaryService.getDictionaryItemsFirstAsString(dataFetchingEnvironment.getArgument("dictionaryType"));
}

但是随后包含了索引列。可以使用

轻松删除
m <- matrix(data=c(2,2,2,2,3,0,2,2), ncol=4)
index <- 1

x <- apply(m,2,FUN=function(x){all(x==m[,index])}) %>% which()
x
[1] 1 2 4