因此,如果我有一个看起来像这样的数据框:
A B C
rowname1 4.5 4 3.2
rowname2 3 23 9
如何让 R 给我包含特定数字的行/列的名称?
即,如果我给出值 3,它会返回
rowname2,A
假设没有重复,您可以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"
可能正在编写一个简单的函数可以帮助你:
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"
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"