这可能比我做的要容易得多。这是使您挂断电话的那些小问题之一,您想知道为什么。
给定数据框,如下所示:
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)
}
}
}
}
其中,行名和列名是实际值。
最佳答案
使用which
和arr.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"
关于r - 根据R中的条件获取data.frame的行和列名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28244457/