所以如果我的数据框看起来像:
A B C
rowname1 4.5 4 3.2
rowname2 3 23 9
如何让R为我提供包含特定数字的行/列的名称?
即。如果我给出值3,它会返回
rowname2,A
答案 0 :(得分:15)
假设没有重复项,您可以将which
与arr.ind
参数结合使用:
df <- data.frame(matrix(sample(1:100,12), ncol=3))
# X1 X2 X3
# 1 84 58 36
# 2 9 40 92
# 3 100 28 78
# 4 15 98 29
index <- which(df==36, arr.ind=TRUE)
# row col
# [1,] 1 3
如果您必须拥有该位置的实际行名和列名,那么只需适当地索引它们:
paste(rownames(df)[index[1]], colnames(df)[index[2]], sep=", ")
# [1] "1, X3"
答案 1 :(得分:4)
可能正在编写一个简单的函数可以帮助你:
Which.names <- function(DF, value){
ind <- which(DF==value, arr.ind=TRUE)
paste(rownames(DF)[ind[1:nrow(ind)]], colnames(DF)[ind[2]], sep=', ')
}
DF <- read.table(text="A B C
rowname1 4.5 4 3.2
rowname2 3 23 9", header=TRUE)
Which.names(DF, value=3)
[1] "rowname2, A"
Which.names(DF, value=4.5)
[1] "rowname1, A"
Which.names(DF, value=9.0)
[1] "rowname2, C"
它还允许您处理重复的值。
DF[1,1] <-3.0
Which.names(DF, value=3)
[1] "rowname1, B" "rowname2, B"
DF[1,2] <- 3
Which.names(DF, value=3)
[1] "rowname1, B" "rowname2, B" "rowname1, B"
答案 2 :(得分:0)
在Jilber的答案代码中存在一些问题,需要改变一点,应该是这样的(R版本3.1.2):
Which.names <- function(DF, value){
ind <- which(DF==value, arr.ind=TRUE)
for (i in 1:nrow(ind)) print(paste(rownames(DF)[ind[i,"row"]], colnames(DF)[ind[i,"col"]], sep=', '))
}
which.names <- function(DF, value){
ind <- which(DF==value, arr.ind=TRUE)
print(paste(rownames(DF)[ind[,"row"]], colnames(DF)[ind[,"col"]], sep=', '))
}
> DF <- read.table(text="A B C
+ rowname1 4.5 4 3.2
+ rowname2 3 23 9", header=TRUE)
> DF
A B C
rowname1 4.5 4 3.2
rowname2 3.0 23 9.0
> Which.names(DF,3)
[1] "rowname2, A"
> which.names(DF,3)
[1] "rowname2, A"
> Which.names(DF,4)
[1] "rowname1, B"
> which.names(DF,4)
[1] "rowname1, B"
> Which.names(DF,9)
[1] "rowname2, C"
> which.names(DF,9)
[1] "rowname2, C"
> DF[1,1] <-3.0
> DF
A B C
rowname1 3 4 3.2
rowname2 3 23 9.0
> Which.names(DF,3)
[1] "rowname1, A"
[1] "rowname2, A"
> which.names(DF,3)
[1] "rowname1, A" "rowname2, A"
> DF[1,2] <- 3
> DF
A B C
rowname1 3 3 3.2
rowname2 3 23 9.0
> Which.names(DF,3)
[1] "rowname1, A"
[1] "rowname2, A"
[1] "rowname1, B"
> which.names(DF,3)
[1] "rowname1, A" "rowname2, A" "rowname1, B"