简体   繁体   English

根据R中的条件获取data.frame的行列名

[英]Get row and column name of data.frame according to condition in R

This is probably much easier than I am making it.这可能比我做的要容易得多。 It is one of those little problems which hangs you up and you wonder why.这是让你挂断的那些小问题之一,你想知道为什么。

Given dataframe as so:给定数据框如下:

a <- c(1,2,3)
b <- c(4,5,6)
test.df <- data.frame(a,b)

How could one use iterate through the values in each column and return the column name and row name if the value = '1'?如果值 = '1',如何使用迭代每列中的值并返回列名和行名?

Something like this:像这样的东西:

for (i in test.df) {
    for (j in i) {
        if (i == 1) {
            print(rowname,columnname)
            }
        }
    }  
}  

Where rowname and columnname are actual values.其中 rowname 和 columnname 是实际值。

Using which and arr.ind=T is a way:使用whicharr.ind=T是一种方法:

Example Data示例数据

a <- c(1,2,3)
b <- c(4,5,6)
test.df <- data.frame(a,b)

Solution and Output解决方案和输出

#test.df==1 gives a TRUE/FALSE matrix
#which with the arr.ind argument=TRUE gives the row/col of the TRUE elements
a <- which(test.df==1,arr.ind=T)

> a
     row col
[1,]   1   1

And then you use the above to get the row and column names:然后你使用上面的来获取行和列名称:

> row.names(test.df[a[,1],] ) #row names
[1] "1"

> names(test.df[a[,2]])       #column names
[1] "a"

Another approach:另一种方法:

> col = colnames(test.df)[apply(test.df, 2, function(u) any(u==1))]
> col
[1] "a"
> row = row.names(test.df)[apply(test.df, 1, function(u) any(u==1))]
> row
[1] "1"

This is an old thread but I am not very satisfied with the previous solutions.这是一个旧线程,但我对以前的解决方案不太满意。

For me the most intuitive is:对我来说最直观的是:

row.names(data)[which(data$feature1==value)]

Which is basically saying: Given the row names of all the data give me those where a given condition is satisfied.这基本上是说:给定所有数据的行名称,给我那些满足给定条件的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM