簡體   English   中英

根據R中的條件獲取data.frame的行列名

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

這可能比我做的要容易得多。 這是讓你掛斷的那些小問題之一,你想知道為什么。

給定數據框如下:

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

如果值 = '1',如何使用迭代每列中的值並返回列名和行名?

像這樣的東西:

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

其中 rowname 和 columnname 是實際值。

使用whicharr.ind=T是一種方法:

示例數據

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

解決方案和輸出

#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

然后你使用上面的來獲取行和列名稱:

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

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

另一種方法:

> 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"

這是一個舊線程,但我對以前的解決方案不太滿意。

對我來說最直觀的是:

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

這基本上是說:給定所有數據的行名稱,給我那些滿足給定條件的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM